
package com.mjsheng.myappstore.server;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.download.DownloadInfo;
import com.lzy.okserver.download.DownloadManager;
import com.lzy.okserver.download.DownloadService;
import com.lzy.okserver.listener.DownloadListener;
import com.mjsheng.myappstore.base.MyApplication;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.download.StorageUtils;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.Utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//  下载管理服务
public class MyDownloadService extends Service {

    private DownloadReceiver downloadReceiver;
    private DownloadManager downloadManager;
    public List<DownloadInfo> allTask;
    private List<String> downloadURL; // 当前下载的任务
    private static final String ACTION_START = "START";
    private static final String ACTION_STOP = "STOP";


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {

        super.onCreate();
        downloadManager = DownloadService.getDownloadManager();
        downloadManager.getThreadPool().setCorePoolSize(1);
        downloadManager.startAllTask();
        allTask = downloadManager.getAllTask();
        for (DownloadInfo downloadInfo : allTask) {
            DownloadListener downloadListener = new MyDownloadListener();
            downloadListener.setUserTag(downloadInfo.getUrl());
            downloadInfo.setListener(downloadListener);
        }
        downloadReceiver = new DownloadReceiver();
        downloadURL = new ArrayList<>();
        /* 注册广播 */
        IntentFilter mScreenOnFilter = new IntentFilter();
        mScreenOnFilter.addAction(Utils.DOWNLOAD_STARTALL_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETE_UPDATE_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_START_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_STOP_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_INITIALIZE_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETE_URL_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETE_PACKAGENAME_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_DELETEALL_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_ALLTASK_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_PACKAGENAME_ACTION);
        MyDownloadService.this.registerReceiver(downloadReceiver, mScreenOnFilter);

        startService(new Intent(this, StepService.class));
        startService(new Intent(this, GuardService.class));
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (downloadManager != null) {
            downloadManager.stopAllTask();
        }
        if (allTask != null) {
            allTask.clear();
            allTask = null;
        }
        downloadURL.clear();
        MyDownloadService.this.unregisterReceiver(downloadReceiver);
        Intent sevice = new Intent(this, DownloadService.class);
        this.startService(sevice);
    }

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

    private class MyDownloadListener extends DownloadListener {

        @Override
        public void onProgress(DownloadInfo downloadInfo) {
            Log.e("mjsheng", "onProgress::::::::" + downloadInfo.getProgress());
            sendDownloadState(downloadInfo);
        }

        @Override
        public void onFinish(DownloadInfo downloadInfo) {
            Log.e("fht", "onFinish");
            sendDownloadState(downloadInfo);
            AppDateInfo info = (AppDateInfo) downloadInfo.getData();
            String s = Settings.System.getString(getContentResolver(), "qch_app_forbid");
            String s1 = s;
            if (!s.contains(info.getApp_baoming())) {
                s1 = s + "," + info.getApp_baoming();
            }
            Settings.System.putString(getContentResolver(), "qch_app_forbid", s1);
            Log.e("SystemSetting", "qch_app_forbid__________" + Settings.System.getString(getContentResolver(), "qch_app_forbid"));

            if (info.getApp_baoming().equals(Utils.YOUNGSYSTEM_APP_TONGBU) || info.getApp_baoming().equals(MyApplication.getAppContext().getPackageName())) {
//                ApkUtils.install(MyApplication.getAppContext(), new File(downloadInfo.getTargetPath()));
                ApkUtils.installApkInSilence(downloadInfo.getTargetPath(), info.getApp_baoming());
                Log.e("fht", "updateTask1");
//                ApkUtils.updateTask(getApplicationContext());

            }
            if (downloadURL.contains(downloadInfo.getUrl())) {
//                ApkUtils.install(MyApplication.getAppContext(), new File(downloadInfo.getTargetPath()));
                if (ApkUtils.getinstallPackage().equals("") || ApkUtils.isAvailable(getApplicationContext(), ApkUtils.getinstallPackage())) {
                    //没有任务或者任务已经安装
                    Log.e("fht", "task package is installed , install new apk ");
                    ApkUtils.installApkInSilence(downloadInfo.getTargetPath(), info.getApp_baoming());
                } else {
                    //更新正在安装的信息，更新任务列表
                    ApkUtils.setInstallIngPackageName("");
                    ApkUtils.updateTask(allTask, getApplicationContext());
                }

                //有bug，会一直回调
                Log.e("fht", "updateTask2");
                downloadURL.remove(downloadInfo.getUrl());
            }
        }

        @Override
        public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
            sendDownloadState(downloadInfo);
        }
    }

    private void sendDownloadState(DownloadInfo downloadInfo) {
        if (downloadInfo == null) return;
        AppDownloadInfo info = new AppDownloadInfo();
        info.setFileName(downloadInfo.getFileName());
        info.setProgress(downloadInfo.getProgress());
        info.setTargetPath(downloadInfo.getTargetPath());
        info.setUrl(downloadInfo.getUrl());
        info.setState(downloadInfo.getState());
        info.setDownloadLength(downloadInfo.getDownloadLength());
        info.setTotalLength(downloadInfo.getTotalLength());
        AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData();
        info.setPackageName(dateInfo.getApp_baoming());
        info.setVersion(dateInfo.getApp_banben());
        info.setData(dateInfo);
        Intent intent = new Intent();
        intent.setAction(Utils.DOWNLOAD_SERVICE_ACTION);
        intent.putExtra("DownloadInfo", info);
        sendBroadcast(intent);
    }

    /**
     * 是否存在该包名的下载任务
     */
    public DownloadInfo getPackageName(String packagename) {
        if (packagename != null) {
            for (DownloadInfo downloadInfo : allTask) {
                AppDateInfo info = (AppDateInfo) downloadInfo.getData();
                if (info.getApp_baoming() != null) {
                    if (info.getApp_baoming().equals(packagename)) {
                        return downloadInfo;
                    }
                }
            }
        }
        return null;
    }


    public class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Utils.DOWNLOAD_STARTALL_ACTION.equals(intent.getAction())) {
                downloadManager.startAllTask();
            } else if (Utils.DOWNLOAD_DELETE_URL_ACTION.equals(intent.getAction())) {
                // 删除标识 下载地址
                String URL = intent.getStringExtra("URL");
                DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL);
                if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                    downloadInfo.setState(10);
                    sendDownloadState(downloadInfo);
                    downloadManager.removeTask(downloadInfo.getUrl(), true);
                }
            } else if (Utils.DOWNLOAD_START_ACTION.equals(intent.getAction())) {
                // 下载
                String URL = intent.getStringExtra("URL");
                AppDateInfo appDateInfo = (AppDateInfo) intent.getSerializableExtra("AppDateInfo");
                if (appDateInfo != null) {
                    GetRequest request = OkGo.get(URL);
                    MyDownloadListener listener = new MyDownloadListener();
                    listener.setUserTag(URL);
                    if (URL != null) {
                        if (downloadManager.getDownloadInfo(URL) == null) {
                            if (!StorageUtils.isFileIsExists("/Android/data/" + context.getPackageName() + "/files/Download")) {
//                                StorageUtils.getFileRoot(context);
                            }
                            downloadManager.addTask(URL, appDateInfo, request, listener);
                            SaveListUtils.addDownLoadList(appDateInfo.getApp_baoming());
                            DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL);
                            AppDownloadInfo info = new AppDownloadInfo();
                            info.setFileName(downloadInfo.getFileName());
                            info.setProgress(downloadInfo.getProgress());
                            info.setTargetPath(downloadInfo.getTargetPath());
                            info.setUrl(downloadInfo.getUrl());
                            info.setState(downloadInfo.getState());
                            info.setDownloadLength(downloadInfo.getDownloadLength());
                            info.setTotalLength(downloadInfo.getTotalLength());
                            AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData();
                            info.setPackageName(dateInfo.getApp_baoming());
                            String s = Settings.System.getString(getContentResolver(), "qch_app_forbid");
                            Settings.System.putString(getContentResolver(), "qch_app_forbid", s + "," + dateInfo.getApp_baoming());
                            Log.e("SystemSetting", "qch_app_forbid__________" + Settings.System.getString(getContentResolver(), "qch_app_forbid"));

                            //2019.9.26
                            info.setVersion(dateInfo.getApp_banben());
                            info.setData(dateInfo);
                            Intent allIntent = new Intent();
                            allIntent.setAction(Utils.DOWNLOAD_NEWSERVICE_ACTION);
                            allIntent.putExtra("addTask", info);
                            sendBroadcast(allIntent);

                        } else {
                            if (!StorageUtils.isFileIsExists(downloadManager.getDownloadInfo(URL).getTargetPath())) {
                                downloadManager.removeTask(URL, true);
//                                StorageUtils.getFileRoot(context);
                            }
                            downloadManager.addTask(URL, appDateInfo, request, listener);
                        }
                        if (!downloadURL.contains(URL)) {
                            downloadURL.add(URL);
                        }
                    }
                } else {
                    if (downloadManager.getDownloadInfo(URL) != null) {
                        downloadManager.restartTask(URL);
                    }
                }
            } else if (Utils.DOWNLOAD_INITIALIZE_ACTION.equals(intent.getAction())) {
                // 初始化item状态
                String URL = intent.getStringExtra("URL");
                DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL);
                if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                    sendDownloadState(downloadInfo);
                }
            } else if (Utils.DOWNLOAD_PACKAGENAME_ACTION.equals(intent.getAction())) {
                // 初始化item状态
                String packageName = intent.getStringExtra("packageName");
                DownloadInfo downloadInfo = getPackageName(packageName);
                if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                    sendDownloadState(downloadInfo);
                }
            } else if (Utils.DOWNLOAD_STOP_ACTION.equals(intent.getAction())) {
                // 暂停标识
                String URL = intent.getStringExtra("URL");
                downloadManager.pauseTask(URL);
                DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL);
                if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                    sendDownloadState(downloadInfo);
                }
            } else if (Utils.DOWNLOAD_DELETE_PACKAGENAME_ACTION.equals(intent.getAction())) {
                // 删除标识 包名
                String packageName = intent.getStringExtra("packageName");
                DownloadInfo downloadInfo = getPackageName(packageName);
                if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                    downloadInfo.setState(10);
                    sendDownloadState(downloadInfo);
                    downloadManager.removeTask(downloadInfo.getUrl(), true);
                }
            } else if (Utils.DOWNLOAD_DELETE_URL_ACTION.equals(intent.getAction())) {
                // 删除标识 下载地址
                String URL = intent.getStringExtra("URL");
                DownloadInfo downloadInfo = downloadManager.getDownloadInfo(URL);
                if (downloadInfo != null) {
                    downloadInfo.setState(10);
                    sendDownloadState(downloadInfo);
                    downloadManager.removeTask(downloadInfo.getUrl(), true);
                }
            } else if (Utils.DOWNLOAD_DELETE_UPDATE_ACTION.equals(intent.getAction())) {
                // 删除 应用更新包
                String packageName = intent.getStringExtra("packageName");
                DownloadInfo downloadInfo = getPackageName(packageName);
                if (downloadInfo != null && downloadInfo.getData() != null) {
                    AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData();
                    PackageManager packageManager = context.getPackageManager();
                    try {
                        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                                0);
                        String version = packInfo.versionName;
                        String oldVersion = dateInfo.getApp_banben();
                        if (oldVersion == null || oldVersion.equals("")) {
                            downloadManager.removeTask(downloadInfo.getUrl(), true);
                        } else if (Utils.isUpdate(oldVersion, version) == true || oldVersion.equals(version)) {
                            downloadManager.removeTask(downloadInfo.getUrl(), true);
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                        downloadInfo.setState(10);
                        sendDownloadState(downloadInfo);
                        downloadManager.removeTask(downloadInfo.getUrl(), true);
                    }
                }
            } else if (Utils.DOWNLOAD_ALLTASK_ACTION.equals(intent.getAction())) {
                downloadManager = DownloadService.getDownloadManager();
                allTask = downloadManager.getAllTask();
                List<AppDownloadInfo> list = new ArrayList<>();
                if (allTask.size() > 0) {
                    for (int i = 0; i < allTask.size(); i++) {
                        DownloadInfo downloadInfo = allTask.get(i);
                        if (downloadInfo != null && StorageUtils.isFileIsExists(downloadInfo.getTargetPath())) {
                            AppDateInfo dateInfo = (AppDateInfo) downloadInfo.getData();
                            if (!dateInfo.getApp_baoming().equals(Utils.YOUNGSYSTEM_APP_TONGBU) && !dateInfo.getApp_baoming().equals(context.getPackageName())) {
                                AppDownloadInfo info = new AppDownloadInfo();
                                info.setFileName(downloadInfo.getFileName());
                                info.setProgress(downloadInfo.getProgress());
                                info.setTargetPath(downloadInfo.getTargetPath());
                                info.setUrl(downloadInfo.getUrl());
                                info.setState(downloadInfo.getState());
                                info.setDownloadLength(downloadInfo.getDownloadLength());
                                info.setTotalLength(downloadInfo.getTotalLength());
                                info.setPackageName(dateInfo.getApp_baoming());
                                info.setVersion(dateInfo.getApp_banben());
                                info.setData(dateInfo);
                                list.add(info);
                            }
                        }
                    }
                }
                Intent allIntent = new Intent();
                allIntent.setAction(Utils.DOWNLOAD_ALLSERVICE_ACTION);
                allIntent.putExtra("allTask", (Serializable) list);
                Log.e("fht", "allTask updateTask：" + allTask.size());
                ApkUtils.updateTask(allTask, getApplicationContext());
                sendBroadcast(allIntent);
            }
        }

    }

}
