package com.kfzs.duanduan;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.appstore.utils.adapter.OnMDLItemChildClickListener;
import com.kfzs.duanduan.adp.DownloadMgrAdapter;
import com.kfzs.duanduan.bean.CompareResult;
import com.kfzs.duanduan.bean.DownloadStatus;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventDownloadHandler;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.ApkUtils;
import com.kfzs.duanduan.utils.dlg.HelperUtils;
import com.kfzs.duanduan.utils.dlg.TitleBarUtils;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.kfzs.duanduan.view.KFProgressButton;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Download manger activity
 * Created by HooRang on 2017/4/10.
 */

public class ActDownloadMgr extends BaseCompatActivity {


    @BindView(R.id.download_mgr_listview)
    ListView lvDownloadMgr;

    @BindView(R.id.download_mgr_empty_view)
    View tvEmptyView;

    /**
     * Download manager list view data's adapter
     */
    DownloadMgrAdapter downloadMgrAdapter;

    /**
     * The service about persistence data and sqlite helper
     */
    DownloadTaskService downloadTaskService;

    /**
     * Data source
     */
    List<DownLoadInfo> downloadTasks;

    //防止手抖，双击；
    private boolean doubleKill = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_mgr);
        TitleBarUtils.getInstance().setTitleFinish(this)
                .setTitle(this, getString(R.string.label_download_mgr))
                .setRightBotton(this, "删除全部", 0, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Aria.download(KFZSApp.getInstance()).removeAllTask(true);
                        downloadTaskService.deleteAllDownloadTask();
                        downloadTasks.clear();
                        downloadMgrAdapter.clear();
                        showDownloadTaskList(false);
                    }
                });

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        downloadTasks = new ArrayList<>();
        downloadTaskService = new DownloadTaskService(this);

        initControlsEvents();
        Aria.download(this).register();

    }

    @Override
    protected void onResume() {
        super.onResume();
        setDownloadTaskData();
    }

    private void initControlsEvents() {

        downloadMgrAdapter = new DownloadMgrAdapter(this);
        lvDownloadMgr.setAdapter(downloadMgrAdapter);
        downloadMgrAdapter.setOnItemChildClickListener(new OnMDLItemChildClickListener() {
            @Override
            public void onItemChildClick(ViewGroup parent, View childView, final int position) {
                if (downloadTasks.size() <= position) {
                    return;
                }
                final DownLoadInfo downloadTask = downloadTaskService.getDownloadTaskByUrl(downloadTasks.get(position).getMDownloadUrl());
                if (null == downloadTask) {
                    return;
                }

                switch (childView.getId()) {
                    case R.id.download_mgr_ib_delete:
                        if (!doubleKill) {
                            doubleKill = true;
                            downloadTaskItemEventDelete(downloadTask, position);
                        }
                        break;
                    case R.id.download_mgr_btn_act:

                        downloadTaskItemEventAction(downloadTask);
                        break;
                    case R.id.download_mgr_iv_icon:
//                        Intent intent = new Intent(ActDownloadMgr.this, ActGameDetails.class);
//                        intent.putExtra(KFIntentKeys.EXTRA_GAME_ID, String.valueOf(downloadTask.getMGameID()));
//                        startActivity(intent);
                        break;
                    default:

                        break;
                }
            }
        });
    }

    private void setDownloadTaskData() {
        downloadTasks.clear();
        downloadTasks.addAll(downloadTaskService.getAllDownloadTasks());

        downloadMgrAdapter.clear();
        downloadMgrAdapter.addMoreDatas(downloadTasks);
        showDownloadTaskList(!downloadTasks.isEmpty());
    }


    /*@Subscribe
    public void onEventMainThread(final DownloadStatus info) {
        if (mOnDownCallback == null) {
            mOnDownCallback = DownBtnUtils.installBtnStatus(downloadMgrAdapter.getmInstallButtonMgrMap());
        }
        EventDownloadHandler
                .newInstance(this, mOnDownCallback)
                .setmTag(TAG)
                .handlDownloadResult(info);
    }*/

    @Subscribe
    public void onEventMainThread(BigEvent bigEvent) {
        if (bigEvent.getEventTypes() == EventTypes.STORAGE_LOW) {
            DialogStorageLow.showDialog(this);
        }
    }

    @Subscribe
    public void onEventMainThread(final DownloadStatus info) {
        EventDownloadHandler.newInstance(this, new EventDownloadHandler.OnDownCallback() {
            @Override
            public void downloading(String url, Integer progress) {
                KFProgressButton targetBtn = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_BUTTON + url);
                ProgressBar pbProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_PROGRESS + url);
                TextView tvProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_TEXTVIEW + url);
                if (tvProgress == null) {
                    return;
                }
                tvProgress.setText(strFormat(ActDownloadMgr.this, info.getFileDownloadedSize(),
                        info.getFileTotalSize()));
                pbProgress.setProgress(info.getDownloadPgrs());
                targetBtn.setText(R.string.downloading);

                setTaskStatusByDownloadUrl(url, DownloadTaskService.STATUS_ING, "");
            }

            @Override
            public void downloadFinish(String downloadUrl) {
                TextView tvProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_TEXTVIEW + info.getDownloadUrl());
                tvProgress.setText(R.string.download_completed);

                setTaskStatusByDownloadUrl(info.getDownloadUrl(), DownloadTaskService.STATUS_FINISH, info.getApkPath());
            }

            @Override
            public void downloadPause(String downloadUrl) {

            }

            @Override
            public void downloadFail(String url) {
                KFProgressButton targetBtn = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_BUTTON + url);
                targetBtn.setText(R.string.download_fail);
                setTaskStatusByDownloadUrl(url, DownloadTaskService.STATUS_FAIL, "");
            }

            @Override
            public void downloadDelete(String downloadUrl) {
                int iTempPosition = -1;
                for (int position = 0; position < downloadTasks.size(); position++) {
                    DownLoadInfo task = downloadTasks.get(position);
                    if (downloadUrl.equals(task.getMDownloadUrl())) {
                        iTempPosition = position;
                        break;
                    }
                }
                if (iTempPosition < 0) {
                    return;
                }
                removeTask(iTempPosition);
            }

            @Override
            public void downloadInit(String downloadUrl) {

            }
        }).setmTag(TAG).handlDownloadResult(info);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //删除任务；
    private void downloadTaskItemEventDelete(DownLoadInfo downloadTask, int position) {
        if (downloadTask.getMDownloadTaskId() != null) {
            downloadTaskService.cancel(downloadTask);
        } else {

        }
        if (!TextUtils.isEmpty(downloadTask.getMApkPath())) {
            new File(downloadTask.getMApkPath()).delete();
        }
        removeTask(position);
        doubleKill = false;
    }

    private void downloadTaskItemEventAction(DownLoadInfo downloadTask) {
        switch (downloadTask.getMStatus()) {
            case DownloadTaskService.STATUS_INIT:
                Log.d(TAG, "Still init status #" + downloadTask.getMDownloadUrl());
                break;
            case DownloadTaskService.STATUS_ING:
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_PAUSE,
                        downloadTask.getMPercent() == null ? 0 : downloadTask.getMPercent(), true);
                break;
            case DownloadTaskService.STATUS_PAUSE:
                int currentDownloadTaskSize = downloadTaskService.getDownloadingTasksCount();
                if (currentDownloadTaskSize >= KFZSApp.MAX_DOWNLOAD_TASK_SIZE) {
                    String strPrompt = String.format(getString(R.string.toast_download_task_out_of_rang), KFZSApp.MAX_DOWNLOAD_TASK_SIZE + "");
                    Toast.makeText(this, strPrompt, Toast.LENGTH_SHORT).show();
                    return;
                }
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_ING,
                        downloadTask.getMPercent() == null ? 0 : downloadTask.getMPercent(), false);
                break;
            case DownloadTaskService.STATUS_FAIL:
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_INIT, 0, false);
                if (null != downloadTask.getMTotalSize() && downloadTask.getMTotalSize() > HelperUtils.getFreeSpace()) {
                    EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.STORAGE_LOW)
                            .setData(downloadTask.getMGameName()));
                }
                break;
            case DownloadTaskService.STATUS_FINISH:
                boolean isPkgInstalled = ApkUtils.getInstance().isPkgInstalled(downloadTask.getMPackageName());
                if (isPkgInstalled) {
                    int apkStatus = ApkUtils.getInstance().comparePkgVersionCode(downloadTask.getMPackageName(), downloadTask.getMVersionCode());
                    if (apkStatus == CompareResult.EQUALS || apkStatus == CompareResult.LT) {
                        ApkUtils.openApplication(this, downloadTask.getMPackageName());
                    } else {
                        changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_ING, 1, false);
                    }
                } else {
                    if (new File(downloadTask.getMApkPath()).exists()) {
                        ApkUtils.installApk(this, downloadTask.getMApkPath());
                    } else {
                        restartTaskByDownloadUrl(downloadTask);
                    }
                }
                break;
            default:
                Log.d(TAG, "Unknown task status#" + downloadTask.getMStatus());
                break;
        }
    }

    private void restartTaskByDownloadUrl(final DownLoadInfo task) {
        downloadTaskService.cancel(task);
        downloadTaskService.deleteDownloadTaskByDownloadUrl(task.getMDownloadUrl());
        downloadTaskService.start(task);//重新下载
        setDownloadTaskData();
    }

    private void changeTaskPersistenceStatus(String downloadUrl, int status, int percent, boolean bPauseTask) {
        boolean isUpdate = downloadTaskService.setDownloadTaskStatus(downloadUrl, status);
        DownLoadInfo downLoadInfo = downloadTaskService.getDownloadTaskByUrl(downloadUrl);
        if (isUpdate) {
            setDownloadTaskData();
            if (bPauseTask) {
                downloadTaskService.pause(downLoadInfo);
            } else {
                downloadTaskService.start(downLoadInfo);

            }
            postDownloadTaskEvents(downloadUrl, status, percent);
        }
    }

    private void setTaskStatusByDownloadUrl(String downloadUrl, int status, String apkPath) {
        int iTempPosition = -1;
        for (int position = 0; position < downloadTasks.size(); position++) {
            DownLoadInfo task = downloadTasks.get(position);
            if (downloadUrl.equals(task.getMDownloadUrl())) {
                iTempPosition = position;
                break;
            }
        }
        if (iTempPosition < 0) {
            return;
        }

        downloadTasks.get(iTempPosition).setMStatus(status);
        downloadTasks.get(iTempPosition).setMApkPath(apkPath);
    }

    private void removeTask(int position) {
        if (downloadTasks.size() == 0
                || downloadTasks.size() < position - 1
                || downloadTasks.get(position) == null) {
            return;
        }
        final String targetUrl = downloadTasks.get(position).getMDownloadUrl();
        if (TextUtils.isEmpty(targetUrl)) {
            return;
        }

        boolean isSuccess = downloadTaskService.deleteDownloadTaskByDownloadUrl(targetUrl);
        if (isSuccess) {
            setDownloadTaskData();
            //延时执行，不然删除消息可能比下载进度信息先到，导致删除后还提示安装中
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    postDownloadTaskEvents(targetUrl, DownloadTaskService.STATUS_DELETE, 0);
                }
            }, 500);
        }
    }


    private void postDownloadTaskEvents(String targetUrl, int status, int percent) {
        if ("".equals(targetUrl)) {
            return;
        }
        DownloadStatus downloadStatusInfo = new DownloadStatus();
        downloadStatusInfo.setStatus(status);
        downloadStatusInfo.setDownloadUrl(targetUrl);
        downloadStatusInfo.setDownloadPgrs(percent);
        EventBus.getDefault().post(downloadStatusInfo);
    }


    public static String strFormat(Context context, Double fileDownloadSize, Double fileTotalSize) {
        DecimalFormat df = new DecimalFormat("######0.0");
        if (fileDownloadSize == null || fileTotalSize == null) {
            return context.getString(R.string.calculating);
        }
        return df.format(fileDownloadSize) + "MB / " + fileTotalSize.intValue() + "MB";
    }

    private void showDownloadTaskList(boolean isShow) {
        tvEmptyView.setVisibility(isShow ? View.GONE : View.VISIBLE);
        lvDownloadMgr.setVisibility(!isShow ? View.GONE : View.VISIBLE);
    }
    @Download.onPre void onPre(DownloadTask task) {
    }
    @Download.onTaskStart void taskStart(DownloadTask task) {
    }
    @Download.onTaskResume void taskResume(DownloadTask task) {
    }
    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
//        downloadTaskService.setDownloadTaskPercent(p, task.getCurrentProgress()/1024d/1024d,task.getFileSize()/1024d/1024d,0,task.getKey());
        try {
            int p = task.getPercent();    //任务进度百分比
            String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
            System.out.println("Aria "+task.getKey()+",p " + p + ", speed = " + speed);
            String url = task.getKey();
            KFProgressButton targetBtn = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_BUTTON + url);
            ProgressBar pbProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_PROGRESS + url);
            TextView tvProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_TEXTVIEW + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText(strFormat(this,task.getCurrentProgress()/1024d/1024d,task.getFileSize()/1024d/1024d));
            pbProgress.setProgress(task.getPercent());
            targetBtn.setText(R.string.downloading);

            setTaskStatusByDownloadUrl(url, DownloadTaskService.STATUS_ING, task.getDownloadPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Download.onTaskStop void taskStop(DownloadTask task) {
//        String url = task.getKey();
//        downloadTaskService.setDownloadTaskStatus(url, DownloadTaskService.STATUS_PAUSE);
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
//        downloadTaskService.deleteDownloadTaskByDownloadUrl(task.getKey());
        try {
            String url = task.getKey();
            int iTempPosition = -1;
            for (int position = 0; position < downloadTasks.size(); position++) {
                DownLoadInfo downLoadInfo = downloadTasks.get(position);
                if (url.equals(downLoadInfo.getMDownloadUrl())) {
                    iTempPosition = position;
                    break;
                }
            }
            if (iTempPosition < 0) {
                return;
            }
            removeTask(iTempPosition);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Download.onTaskFail void taskFail(DownloadTask task) {
//        downloadTaskService.setDownloadTaskStatus(task.getKey(), DownloadTaskService.STATUS_FAIL);
        try {
            String url = task.getKey();
            KFProgressButton targetBtn = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_BUTTON + url);
            targetBtn.setText(R.string.download_fail);
            setTaskStatusByDownloadUrl(url, DownloadTaskService.STATUS_FAIL, task.getDownloadPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
//        downloadTaskService.setDownloadTaskFinish(task.getKey(), task.getDownloadPath());
        try {
            TextView tvProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_TEXTVIEW + task.getKey());
            tvProgress.setText(R.string.download_completed);

            setTaskStatusByDownloadUrl(task.getKey(), DownloadTaskService.STATUS_FINISH, task.getDownloadPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApkUtils.installApk(ActDownloadMgr.this, task.getDownloadPath());
    }

}







