package com.sheep.gamegroup.view.activity;

import android.content.Context;
import android.text.TextUtils;
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.kfzs.appstore.utils.adapter.OnMDLItemChildClickListener;
import com.kfzs.duanduan.utils.ApkUtils;
import com.kfzs.duanduan.view.KFProgressButton;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.OkDownload;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.event.EventDownloadHandler;
import com.sheep.gamegroup.event.EventTypes;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.model.entity.DownloadStatus;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.view.adapter.DownloadMgrAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

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 static com.kfzs.duanduan.utils.ApkUtils.EQUALS;
import static com.kfzs.duanduan.utils.ApkUtils.LT;


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

public class ActDownloadMgr extends BaseActivity {


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

    @BindView(R.id.empty_view)
    View empty_view;

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

    /**
     * The service about persistence data and sqlite helper
     */
    DownloadUtil downloadUtil;

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

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


    @Override
    protected int getLayoutId() {
        return R.layout.activity_download_mgr;
    }

    @Override
    public void initView() {
        TitleBarUtils.getInstance().setTitleFinish(this)
                .setShowOrHide(this, true)
                .setTitleFinish(this)
                .setTitle(this, getString(R.string.label_download_mgr))
                .setRightBtn(this, "删除全部", 0, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            downloadUtil.deleteAllDownloadTask();
                            downloadTasks.clear();
                            downloadMgrAdapter.clear();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            ClassFileHelper.getInstance().clearDir();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        showDownloadTaskList(false);
                    }
                });
    }

    @Override
    public void initListener() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        downloadTasks = new ArrayList<>();
        downloadUtil = new DownloadUtil();
        initControlsEvents();
    }

    @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 = downloadUtil.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(downloadUtil.getAllDownloadTasks());

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

    @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, DownloadUtil.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(), DownloadUtil.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, DownloadUtil.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("ActDownloadMgr").handlDownloadResult(info);

    }


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

    //删除任务；
    private void downloadTaskItemEventDelete(DownLoadInfo downloadTask, int position) {
        if (downloadTask.getMDownloadTaskId() != null) {
            downloadUtil.delete(downloadTask);
            removeTask(position);
        }
        doubleKill = false;
    }

    public static final int MAX_DOWNLOAD_TASK_SIZE = 5;

    private void downloadTaskItemEventAction(DownLoadInfo downloadTask) {
        switch (downloadTask.getMStatus()) {
            case DownloadUtil.STATUS_INIT:
                break;
            case DownloadUtil.STATUS_ING:
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadUtil.STATUS_PAUSE,
                        downloadTask.getMPercent() == null ? 0 : downloadTask.getMPercent(), true);
                break;
            case DownloadUtil.STATUS_PAUSE:
                int currentDownloadTaskSize = downloadUtil.getDownloadingTasksCount();
                if (currentDownloadTaskSize >= MAX_DOWNLOAD_TASK_SIZE) {
                    String strPrompt = String.format(getString(R.string.toast_download_task_out_of_rang), MAX_DOWNLOAD_TASK_SIZE + "");
                    G.shortToast(strPrompt);
                    return;
                }
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadUtil.STATUS_ING,
                        downloadTask.getMPercent() == null ? 0 : downloadTask.getMPercent(), false);
                break;
            case DownloadUtil.STATUS_FAIL:
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadUtil.STATUS_INIT, 0, false);
                if (null != downloadTask.getMTotalSize() && downloadTask.getMTotalSize() > G.getFreeSpace()) {
                    EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.STORAGE_LOW)
                            .setData(downloadTask.getMGameName()));
                }
                break;
            case DownloadUtil.STATUS_FINISH:
                boolean isPkgInstalled = ApkUtils.getInstance().isPkgInstalled(downloadTask.getMPackageName());
                if (isPkgInstalled) {
                    int apkStatus = ApkUtils.getInstance().comparePkgVersionCode(downloadTask.getMPackageName(), downloadTask.getMVersionCode());
                    switch (apkStatus) {
                        case EQUALS:
                        case LT:
                            ApkUtils.openApplication(this, downloadTask.getMPackageName());
                            break;
                        default:
                            changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadUtil.STATUS_ING, 1, false);
                            break;
                    }
                } else {
                    if (!TextUtils.isEmpty(downloadTask.getMApkPath()) && new File(downloadTask.getMApkPath()).exists()) {
                        ApkUtils.installApk(this, downloadTask.getMApkPath());
                    } else {
                        restartTaskByDownloadUrl(downloadTask);
                    }
                }
                break;
            default:
                break;
        }
    }

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

    private void changeTaskPersistenceStatus(String downloadUrl, int status, int percent, boolean bPauseTask) {
        DownLoadInfo downLoadInfo = downloadUtil.setDownloadTaskStatus(downloadUrl, status);
        if (downLoadInfo != null) {
            DownloadTask task = DownloadUtil.getTask(downLoadInfo);
            if (bPauseTask) {
                OkDownload.with().downloadDispatcher().cancel(task);
            } else {
                downloadUtil.start(downLoadInfo);
            }
        }
    }

    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 = downloadUtil.deleteDownloadTaskByDownloadUrl(targetUrl);
        if (isSuccess) {
            setDownloadTaskData();
        }
    }


    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 / (1024 * 1024)) + "MB / " + (fileTotalSize.intValue() / (1024 * 1024)) + "MB";
    }

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

    private void showDownloadTaskList(boolean isShow) {
        CommonUtil.getInstance().updateEmptyView(empty_view, !isShow);
        lvDownloadMgr.setVisibility(!isShow ? View.GONE : View.VISIBLE);
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    protected void running(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();
            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.getMDownloadedSize(), task.getMTotalSize()));
            pbProgress.setProgress(task.getMPercent());
            targetBtn.setText(R.string.downloading);

            setTaskStatusByDownloadUrl(url, DownloadUtil.STATUS_ING, task.getMApkPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void taskStop(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();
            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.getMDownloadedSize(), task.getMTotalSize()));
            pbProgress.setProgress(task.getMPercent());
            targetBtn.setText(R.string.has_pause);

            setTaskStatusByDownloadUrl(url, DownloadUtil.STATUS_PAUSE, task.getMApkPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void taskCancel(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();
            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();
        }
    }

    void taskFail(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();
            KFProgressButton targetBtn = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_BUTTON + url);
            targetBtn.setText(R.string.download_fail);
            setTaskStatusByDownloadUrl(url, DownloadUtil.STATUS_FAIL, task.getMApkPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void taskComplete(DownLoadInfo task) {
        try {
            TextView tvProgress = lvDownloadMgr.findViewWithTag(DownloadMgrAdapter.PUBLIC_TAG_PREFIX_TEXTVIEW + task.getMDownloadUrl());
            tvProgress.setText(R.string.download_completed);

            setTaskStatusByDownloadUrl(task.getMDownloadUrl(), DownloadUtil.STATUS_FINISH, task.getMApkPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApkUtils.installApk(ActDownloadMgr.this, task.getMApkPath());
    }

    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        if (event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            switch (event.getEventTypes()) {
                case DOWNLOAD_RUNNING:
                    running(task);
                    break;
                case DOWNLOAD_STOP:
                    taskStop(task);
                    break;
                case DOWNLOAD_COMPLETE:
                    taskComplete(task);
                    break;
                case DOWNLOAD_CANCEL:
//                    taskCancel(task);
                    break;
                case DOWNLOAD_FAIL:
                    taskFail(task);
                    break;
            }
        }
    }
}







