package com.sheep.jiuyan.samllsheep.service;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.duanduan.utils.ApkUtils;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.event.EventTypes;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.FindApp;
import com.sheep.gamegroup.model.entity.PlayGameEntity;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.util.ActivityManager;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;

/**
 * @auther realicing
 * 自动更新的Service
 */

public class DownloadService extends Service {

    private DownloadUtil downloadUtil;

    @Override
    public void onCreate() {
        super.onCreate();
        Aria.download(this).register();
        downloadUtil = new DownloadUtil(this);
    }
    public static final String ON_PRE = "onPre";
    public static final String RUNNING = "running";
    public static final String HAS_SHOW = "hasShow";

    @Download.onPre
    void onPre(final DownloadTask task) {
        LogUtil.println("DownloadService", "onPre", task.getKey(), task.getTaskName());

        Observable.just(1).delay(10_000L, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        String taskStatus = DataUtil.getAsString(String.format(Locale.CHINA, "hasShow[%s]", task.getKey()), ON_PRE);
                        switch (taskStatus) {
                            case ON_PRE:
                                DownLoadInfo downloadInfo = downloadUtil.getDownloadTaskByUrl(task.getKey());
                                String taskName = downloadInfo != null ? downloadInfo.getMGameName() : task.getTaskName();
                                DataUtil.putAsString(String.format(Locale.CHINA, "hasShow[%s]", task.getKey()), HAS_SHOW);
                                ViewUtil.showMsgDialog(ActivityManager.getInstance().currentActivity(), new DialogConfig().setTitle("提示")
                                        .setMsg("任务【"+taskName+"】下载无响应，是否使用其它下载方式（在任务列表中长按也可选择其它下载方式）").setBtnLeftText("取消").setBtnRightText("确定")
                                        .setBtnRightOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                showDownloadType(task.getKey(), task.getTaskName());
                                            }
                                        }));
                                break;
                        }
                    }
                });
    }

    @Download.onTaskStart
    void taskStart(DownloadTask task) {
        LogUtil.println("DownloadService", "taskStart", task.getKey(), task.getTaskName());
    }

    @Download.onTaskResume
    void taskResume(DownloadTask task) {
        LogUtil.println("DownloadService", "taskResume", task.getKey(), task.getTaskName());
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        LogUtil.println("DownloadService", "running", task.getKey(), task.getTaskName(), task.getPercent());
        DataUtil.putAsString(String.format(Locale.CHINA, "hasShow[%s]", task.getKey()), RUNNING);
        downloadUtil.setDownloadTaskPercent(task.getPercent(), task.getCurrentProgress() / 1024d / 1024d, task.getFileSize() / 1024d / 1024d, 0, task.getKey());
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.GENERATION_ACCOUNT_REFRESH_ADAPTER).setData(task));
    }

    @Download.onTaskStop
    void taskStop(DownloadTask task) {
        LogUtil.println("DownloadService", "taskStop", task.getKey(), task.getTaskName());
        downloadUtil.setDownloadTaskStatus(task.getKey(), DownloadUtil.STATUS_PAUSE);
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.DOWNLOAD_STOP).setData(task));
    }

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

    @Download.onTaskCancel
    void taskCancel(DownloadTask task) {
        LogUtil.println("DownloadService", "taskCancel", task.getKey(), task.getTaskName());
        downloadUtil.deleteDownloadTaskByDownloadUrl(task.getKey());
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.DOWNLOAD_CANCEL).setData(task));
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task) {
        LogUtil.println("DownloadService", "taskFail", task.getKey(), task.getTaskName());
        downloadUtil.setDownloadTaskStatus(task.getKey(), DownloadUtil.STATUS_FAIL);
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.DOWNLOAD_FAIL).setData(task));
        //空间不足，弹框提示
        try {
            if (0 <= task.getFileSize() && task.getFileSize() > G.getFreeSpaceB()) {
                DialogStorageLow.showDialog(DownloadService.this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        LogUtil.println("DownloadService", "taskComplete", task.getKey(), task.getTaskName());
        downloadUtil.setDownloadTaskFinish(task.getKey(), task.getDownloadPath());
        ApkUtils.installApk(getApplicationContext(), task.getDownloadPath());
        EventBus.getDefault().post(new BigEvent().setEventTypes(EventTypes.DOWNLOAD_COMPLETE).setData(task));
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }






    public static void setDownLoadLongClick(View view, final TaskEty task) {
        if(task != null && task.needDownloadApp())
            setDownLoadLongClick(view, task.getDownload_link(), task.getTask_name());
    }
    public static void setDownLoadLongClick(View view, final FindApp task) {
        if(task != null && !TextUtils.isEmpty(task.getDownload_link()))
            setDownLoadLongClick(view, task.getDownload_link(), task.getTask_name());
    }
    public static void setDownLoadLongClick(View view, final PlayGameEntity task) {
        if(task != null && task.isCanDownload())
            setDownLoadLongClick(view, task.getDownload_link(), task.getTask_name());
    }

    public static void setDownLoadLongClick(View view, final String link, final String taskName) {
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                showDownloadType(link, taskName);
                return true;
            }
        });
    }

    private static void showDownloadType(final String link, final String taskName) {
        final Activity activity = ActivityManager.getInstance().currentActivity();
        if (activity == null) {
            return;
        }
        final String[] items = {"复制下载地址", "系统下载", "浏览器下载"};
        AlertDialog dialog = new AlertDialog.Builder(activity).setTitle("请选择操作")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            switch (items[which]) {
                                case "复制下载地址":
                                    copyDownloadLink(link);
                                    break;
                                case "系统下载":
                                    sysDownload(activity, link, taskName);
                                    break;
                                case "浏览器下载":
                                    webDownload(activity, link);
                                    break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            G.showToast(e.getMessage());
                        }
                    }
                }).create();
        dialog.show();
    }

    private static void copyDownloadLink(final String link) {
        if (StringUtils.CopyText(link)) {
            G.showToast("已经复制游戏下载链接");
        }
    }

    private static void sysDownload(final Context context, String link, String taskName) {
        sysDownload(context, link, taskName, String.format(Locale.CHINA, "下载小绵羊任务【%s】中的app", taskName), taskName + link.hashCode() + ".apk", "系统开始下载apk");
    }

    public static void sysDownload(final Context context, String downloadLink, String title, String description, String fileName, String toast) {
        // 创建下载请求
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadLink));

        /*
         * 设置在通知栏是否显示下载通知(下载进度), 有 3 个值可选:
         *    VISIBILITY_VISIBLE:                   下载过程中可见, 下载完后自动消失 (默认)
         *    VISIBILITY_VISIBLE_NOTIFY_COMPLETED:  下载过程中和下载完成后均可见
         *    VISIBILITY_HIDDEN:                    始终不显示通知
         */
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        // 设置通知的标题和描述
        request.setTitle(title);
        request.setDescription(description);

        /*
         * 设置允许使用的网络类型, 可选值:
         *     NETWORK_MOBILE:      移动网络
         *     NETWORK_WIFI:        WIFI网络
         *     NETWORK_BLUETOOTH:   蓝牙网络
         * 默认为所有网络都允许
         */
//                     request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);

        // 添加请求头
        // request.addRequestHeader("User-Agent", "Chrome Mozilla/5.0");
        if (fileName != null) {
            // 设置下载文件的保存位置
            File saveFile = new File(DIR, fileName);
            request.setDestinationUri(Uri.fromFile(saveFile));
        }

        /*
         * 2. 获取下载管理器服务的实例, 添加下载任务
         */
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (manager != null) {
            // 将下载请求加入下载队列, 返回一个下载ID
            long downloadId = manager.enqueue(request);
            if (toast != null)
                G.showToast(toast);
        }
    }

    public static void webDownload(final Context context, String downloadLink) {
        if (context instanceof Activity) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse(downloadLink));
            context.startActivity(intent);
            G.showToast("浏览器开始下载apk");
        }
    }
}
