package com.sheep.gamegroup.helper;

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

import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTarget;
import com.arialyy.aria.core.inf.IEntity;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.model.api.IDownload;
import com.sheep.gamegroup.view.activity.TaskDetailAct;
import com.sheep.jiuyan.samllsheep.R;
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) {
        if(mDownloadTaskService == null){
            mDownloadTaskService = new DownloadTaskService(activity);
        }
        TaskDetailAct.setBtnStr(iTask, mDownloadTaskService, 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);
            }
        });
        down_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(callBack != null)
                    callBack.call(-1);
                downloadApp(activity, iTask);
            }
        });
    }

    private DownloadTaskService mDownloadTaskService;
    private DownloadTarget downloadTarget;

    /**
     * @param activity
     * @param task
     *   //下载应用
     */
    private void downloadApp(Activity activity, IDownload task) {
        switch (downLoadType){
            case DownloadTaskService.STATUS_INIT://可以下载
                if(TextUtils.isEmpty(task.getDownload_link()) || !task.getDownload_link().contains("http")){
                    G.showToast(R.string.error_download_link);
                    return;
                }
                this.downloadTarget = Aria.download(activity).load(task.getDownload_link());
                final DownLoadInfo downLoadInfo = mDownloadTaskService.getDownloadTaskByUrl(task);
                if(this.downloadTarget != null) {
                    if (this.downloadTarget.getTaskState() == IEntity.STATE_RUNNING) {
                        this.downloadTarget.stop();
                    } else if (this.downloadTarget.getTaskState() == IEntity.STATE_FAIL) {
                        this.downloadTarget.cancel(true);
                        this.downloadTarget.removeRecord();
                    } else {
                        mDownloadTaskService.start(downLoadInfo);
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if(mDownloadTaskService.addDownloadTask(downLoadInfo)){//添加数据到数据库，可以在下载管理中看到
                                //发送红点信息
                                EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.TIPS_DOWN_ICON));
                            }
                        }
                    }).start();
                }
                break;
            case DownloadTaskService.STATUS_FINISH://已经下载完成，可以安装
                String path = PackageUtil.isExistsFile(task.getPackage_names());
                if(TextUtils.isEmpty(path)){//数据库保存有下载完成的状态，但是应用已经被删除，需要修复其下载状态
                    if(TextUtils.isEmpty(task.getDownload_link()) || !task.getDownload_link().contains("http")){
                        G.showToast(R.string.error_download_link);
                        return;
                    }
                    this.downloadTarget = Aria.download(activity).load(task.getDownload_link());
                    if(this.downloadTarget != null) {
                        this.downloadTarget.cancel(true);
                        this.downloadTarget.removeRecord();
                        mDownloadTaskService.start(mDownloadTaskService.getDownloadTaskByUrl(task));
                        mDownloadTaskService.setDownloadTaskStatus(task.getDownload_link(), DownloadTaskService.STATUS_INIT);
                        downLoadType = DownloadTaskService.STATUS_INIT;
                    }
                } else {
                    ApkUtils.installApk(activity, PackageUtil.isExistsFile(task.getPackage_names()));
                }
                break;
            case DownloadTaskService.STATUS_INSTALLED://已经安装，可以试玩
                PackageUtil.startApp(activity, task.getPackage_names());
                break;
        }
    }

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