package com.sheep.gamegroup.helper;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.OkDownload;
import com.liulishuo.okdownload.StatusUtil;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.event.EventTypes;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.util.DownloadUtil;
import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.model.api.IDownload;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.gamegroup.view.activity.TaskDetailAct;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;

import org.greenrobot.eventbus.EventBus;

import rx.functions.Action1;

/**
 * Created by realicing on 2018/7/3.
 * realicing@sina.com
 * 下载游戏辅助类
 */
public class DownloadHelper {
    private int downLoadType;
    /**
     * 更新游戏下载与响应点击
     * @param activity
     * @param iTask
     * @param down_tv
     */
    public void updateDownloadTaskView(final Activity activity, final IDownload iTask, final TextView down_tv) {
        updateDownloadTaskView(activity, iTask, down_tv, null);
    }
    public void updateDownloadTaskView(final Activity activity, final IDownload iTask, final TextView down_tv, final Action1<Object> callBack) {
        updateDownloadTaskView(activity, iTask, down_tv, callBack,0);
    }
    public void updateDownloadTaskView(final Activity activity, final IDownload iTask, final TextView down_tv, final Action1<Object> callBack,int type) {
        final boolean showSimpleText = down_tv.getText().length() < 4;
        if(downloadUtil == null){
            downloadUtil = new DownloadUtil();
        }
        TaskDetailAct.setBtnStr(iTask, downloadUtil, new Action1<Object>() {
            @Override
            public void call(Object o) {
                if(o instanceof Integer){
                    downLoadType = (int) o;
                } else if( o instanceof String){
                    down_tv.setText((String) o);
                } else if( o instanceof Boolean){
                    down_tv.setEnabled((Boolean) o);
                }
//                if(callBack != null)
//                    callBack.call(o);
            }
        }, showSimpleText);
        if(type == 0){
            down_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(callBack != null)
                        callBack.call(-1);
                    downloadApp(activity, iTask);
                }
            });
        }
    }

    private DownloadUtil downloadUtil;

    /**
     * @param activity
     * @param download
     *   //下载应用
     */
    private void downloadApp(Activity activity, IDownload download) {
        switch (downLoadType){
            case DownloadUtil.STATUS_INIT://可以下载
                final DownloadTask task;
                if (TextUtils.isEmpty(download.getDownload_link()) || !download.getDownload_link().contains("http")) {
                    G.showToast(R.string.error_download_link);
                    return;
                }
                task = DownloadUtil.getTask(download);
                final StatusUtil.Status statusOnStore = StatusUtil.getStatus(task);
                final DownLoadInfo downLoadInfo = downloadUtil.getDownloadTaskByUrl(download);
                switch (statusOnStore) {
                    case RUNNING:
                    case PENDING://等待的
                        OkDownload.with().downloadDispatcher().cancel(task);
                        break;
                    case IDLE://空闲的
                    case UNKNOWN:
                        downloadUtil.start(downLoadInfo);
                        Jump2View.getInstance().startDownloadService(activity, downLoadInfo);
                        break;
                    case COMPLETED://有可能之前已经下载完成，但是数据库里已经没有数据了，这时只需要修改状态
                        if(task.getFile() != null) {
                            if(downloadUtil.checkFinish(downLoadInfo)){//检查文件是否真的完成
                                DownLoadInfo newDownloadInfo = downloadUtil.setDownloadTaskFinish(task.getUrl(), task.getFile().getAbsolutePath());
                                downLoadType = DownloadUtil.STATUS_FINISH;
                                EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.DOWNLOAD_COMPLETE).setData(newDownloadInfo));
                            } else {//重新开始下载
                                downloadUtil.delete(downLoadInfo);
                                downloadUtil.start(downloadUtil.getDownloadTaskByUrl(download));
                                downloadUtil.setDownloadTaskStatus(download.getDownload_link(), DownloadUtil.STATUS_INIT);
                                downLoadType = DownloadUtil.STATUS_INIT;
                            }
                        }
                        break;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (downloadUtil.addDownloadTask(downLoadInfo)) {
                            //发送红点信息
                            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.TIPS_DOWN_ICON));
                        }
                    }
                }).start();
                UMConfigUtils.onEvent(UMConfigUtils.Event.TASK_DOWNLOAD);
                break;
            case DownloadUtil.STATUS_FINISH://已经下载完成，可以安装
                String path = PackageUtil.isExistsFile(download.getPackage_names(), download.getDownload_link());
                if(TextUtils.isEmpty(path)){//数据库保存有下载完成的状态，但是应用已经被删除，需要修复其下载状态
                    if(TextUtils.isEmpty(download.getDownload_link()) || !download.getDownload_link().contains("http")){
                        G.showToast(R.string.error_download_link);
                        return;
                    }
                    final DownLoadInfo oldDownloadInfo = downloadUtil.getDownloadTaskByUrl(download);
                    if(oldDownloadInfo != null) {
                        downloadUtil.delete(oldDownloadInfo);
                        downloadUtil.start(downloadUtil.getDownloadTaskByUrl(download));
                        downloadUtil.setDownloadTaskStatus(download.getDownload_link(), DownloadUtil.STATUS_INIT);
                        downLoadType = DownloadUtil.STATUS_INIT;
                    }
                } else {
                    ApkUtils.installApk(SheepApp.getInstance(), path);
                }
                break;
            case DownloadUtil.STATUS_INSTALLED://已经安装，可以试玩
                PackageUtil.startApp(activity, download.getPackage_names());
                break;
        }
    }

    /**
     * 更新下载状态
     * @param status
     */
    public void updateState(int status) {
        downLoadType = status;
    }

    public int getDownLoadType() {
        return downLoadType;
    }
}
