package com.tofly.ghrq_route.module.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.tofly.ghrq_route.module.map.domain.MapEvent;
import com.tofly.ghrq_route.common.ui.activity.DownloadMapActivity;
import com.tofly.ghrq_route.common.ui.dialog.DownloadListDialog;

import org.greenrobot.eventbus.EventBus;

public class DownloadReceiver extends BroadcastReceiver {

    public static final String DownloadReceiverFinished = "com.tofly.route.downloadreceiver.finish";
    public static final String DownloadReceiverProgress= "com.tofly.route.downloadreceiver.progress";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (context instanceof DownloadMapActivity){
            Bundle bundle = intent.getExtras();
            if (action == DownloadReceiverFinished){
                DownloadMapActivity downloadMapActivity = (DownloadMapActivity) context;
                if (bundle != null){
                    String filename = bundle.getString(DownloadListDialog.FILENAME);
                    String dataid = bundle.getString(DownloadListDialog.ID);
                    int position = bundle.getInt(DownloadListDialog.POSITION);
                    int result = bundle.getInt("result");
                    downloadMapActivity.refreshDownloadState(filename, dataid, position, result);
                }
                EventBus.getDefault().post(new MapEvent(MapEvent.DOWNLOAD_PIPE_OK,null));
            }else if (action == DownloadReceiverProgress){
                DownloadMapActivity downloadMapActivity = (DownloadMapActivity) context;
                if (bundle != null){
                    int downloaded = bundle.getInt("current", 0);
                    int total = bundle.getInt("total", 0);
                    int progress = bundle.getInt("progress", 0);
                    String filename = bundle.getString(DownloadListDialog.FILENAME);
                    String dataid = bundle.getString(DownloadListDialog.ID);
                    int position = bundle.getInt(DownloadListDialog.POSITION);
                    downloadMapActivity.updateDownloadProgress(downloaded, total, progress,
                            filename, dataid, position);
                }
            }
        }

    }
}
