package com.sunzee.service;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.hawk.Hawk;
import com.sunzee.base.BaseApplication;
import com.sunzee.utils.FileUtil;
import com.sunzee.utils.SharedPreferencesUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class DownPresenter {
    static final String TAG = "DownPresenter";
    Context context = BaseApplication.getContext();
    private DownloadManager mDownloadManager;
    private boolean isRuning = true;
    private DownPresenter.ProgressUpdate progressUpdate;

    private DownPresenter() {
        String text = "";
        Object systemService = context.getSystemService(Context.DOWNLOAD_SERVICE);
        mDownloadManager = (DownloadManager) systemService;
    }

    private static DownPresenter mDownPresenter;

    public static DownPresenter getInstance() {
        if (mDownPresenter == null) {
            synchronized (DownPresenter.class) {
                mDownPresenter = new DownPresenter();
            }
        }
        return mDownPresenter;
    }

    public void onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            Bundle downloadBundle = intent.getBundleExtra("download");
            if (downloadBundle != null) {
                String downloadUrl = downloadBundle.getString("downloadUrl");
                String title = downloadBundle.getString("title");
                String downloadtype = downloadBundle.getString("downloadtype");
                String name = downloadBundle.getString("download_name");
                int screenType = downloadBundle.getInt("scrrentype");

                if (downloadtype.equals("apk")) {
                    //下载apk
                    String downloadApkUrl = downloadBundle.getString("downloadApkUrl");
                    if (!TextUtils.isEmpty(downloadApkUrl)) {
                        long downloadId = downloadApk1(downloadApkUrl, title, downloadtype);
                        mTaskId = downloadId;
                        //保存当前taskid
                        isRuning = true;
                        startQuery();
                        SharedPreferencesUtils.setParam("taskid", downloadId);
                        String filename = (String) SharedPreferencesUtils.getParam("apkname", "");
                        //保存当前的下载文件名字以及对应的id
                        Map<Long, String> map = new HashMap<>();
                        map.put(downloadId, filename);
                        Hawk.put("download", map);
                    }
                } else {
                    if (!TextUtils.isEmpty(downloadUrl)) {
                        //开始下载
                        long downloadId = downloadAd(downloadUrl, title, downloadtype, screenType);
                        //保存当前taskid
                        SharedPreferencesUtils.setParam("taskid", downloadId);
                        String filename = (String) SharedPreferencesUtils.getParam("filename", "");
                        //保存当前的下载文件名字以及对应的id
                        Map<Long, String> map = new HashMap<>();
                        map.put(downloadId, filename);
                        Hawk.put("download", map);
                    }
                }
            }
        }
    }

    /**
     * 下载广告数据
     *
     * @param url
     * @param title
     * @return 下载taskid
     */
    private long downloadAd(String url, String title, String downloadtype, int screenType) {
        Log.d(TAG, "downloadAd: url=" + url);
        Uri downloadUri = Uri.parse(url);
        Log.d(TAG, "downloadAd: getPath=" + downloadUri.getPath());
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        String apkName = title + "." + downloadtype;
        DownloadManager mDownloadManager = null;
        if (screenType == 0) {
            Hawk.put("screen_type", 0);
            Log.d(TAG, "downloadAd: 下载：" + apkName);
            File externalFilesDir = new File("/leftvideoimg");
            if (externalFilesDir == null || !externalFilesDir.exists()) {
                externalFilesDir.mkdir();
            }
            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/leftvideoimg/" + apkName);
            if (file != null && file.exists()) {
                file.delete();
            }

            request.setDestinationInExternalPublicDir("/leftvideoimg", apkName);
            //保存当前名字
            SharedPreferencesUtils.setParam("filename", apkName);
            request.setVisibleInDownloadsUi(true);
            request.setTitle(title);
            mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        } else {
            Hawk.put("screen_type", 1);
            File externalFilesDir = new File("/rightvideoimg");
            if (externalFilesDir == null || !externalFilesDir.exists()) {
                externalFilesDir.mkdir();
            }
            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/rightvideoimg/" + apkName);
            if (file != null && file.exists()) {
                file.delete();
            }
            Log.d(TAG, "downloadAd: 下载：" + apkName);
            request.setDestinationInExternalPublicDir("/rightvideoimg", apkName);
            //保存当前名字
            SharedPreferencesUtils.setParam("filename", apkName);
            request.setVisibleInDownloadsUi(true);
            request.setTitle(title);
            mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        }

        return mDownloadManager.enqueue(request);
    }


    /**
     * 下载apk
     *
     * @param url
     * @param title
     * @return 下载taskid
     */
    private long downloadApk1(String url, String title, String downloadtype) {
        Uri downloadUri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        String apkName = "mht" + "." + "apk";
        File externalFilesDir = context.getExternalFilesDir("apk");
        File file1 = new File(Environment.getExternalStorageDirectory().getPath() + "/apk/");
        if (file1.exists()) {
            FileUtil.deleteFile(file1);
        }
        if (externalFilesDir == null || !externalFilesDir.exists()) {
            externalFilesDir.mkdir();
        }
        File file = context.getExternalFilesDir("apk" + "/" + "mht.apk");
        Log.d(TAG, "downloadApk1: 下载:" + file.getAbsolutePath());
        if (file != null && file.exists()) {
            file.delete();
        }

        request.setDestinationInExternalPublicDir("/apk", apkName);
        //保存当前名字
        SharedPreferencesUtils.setParam("apkname", apkName);
        request.setVisibleInDownloadsUi(true);
        request.setTitle(title);
        DownloadManager mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Log.d(TAG, "downloadApk1: 下载apk");
        long enqueue = mDownloadManager.enqueue(request);
        startQuery();
        return enqueue;
    }


    private long mTaskId;


    //apk 下载进度监听
    private final DownPresenter.QueryRunnable mQueryProgressRunnable = new QueryRunnable();
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1001) {

                Log.d(TAG, "handleMessage msg.arg1:  " + msg.arg1);
                Log.d(TAG, "handleMessage msg.arg2: " + msg.arg2);
                if (progressUpdate != null) {
                    progressUpdate.onProgressUpdate(msg.arg1, msg.arg2);
                }
            }
        }
    };

    //查询下载进度
    private class QueryRunnable implements Runnable {
        @Override
        public void run() {
            queryState();
            Log.d(TAG, "QueryRunnablerun: ");
            if (isRuning) {
                mHandler.postDelayed(mQueryProgressRunnable, 100);
            }
        }
    }

    //更新下载进度
    private void startQuery() {
        if (mTaskId != 0) {
            mHandler.post(mQueryProgressRunnable);
            Log.d(TAG, "startQuery: ");
        }
    }

    //查询下载进度
    private void queryState() {
        // 通过ID向下载管理查询下载情况，返回一个cursor
        Cursor c = mDownloadManager.query(new DownloadManager.Query().setFilterById(mTaskId));
        if (c != null && c.moveToFirst()) {
            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
            int status = c.getInt(columnIndex);
            switch (status) {
                case DownloadManager.STATUS_RUNNING:
                    Log.d(TAG, "queryState: 下载中");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    Log.d(TAG, "queryState: 下载成功");
                    stopQuery();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Log.d(TAG, "queryState: 下载失败");
                    break;
            }
        }
        if (c == null) {
        } else { // 以下是从游标中进行信息提取
            if (!c.moveToFirst()) {
                if (!c.isClosed()) {
                    c.close();
                }
                return;
            }
            int mDownload_so_far = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            int mDownload_all = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            Message msg = Message.obtain();
            if (mDownload_all > 0) {
                msg.what = 1001;
                msg.arg1 = mDownload_so_far;
                msg.arg2 = mDownload_all;
                mHandler.sendMessage(msg);
            }
            if (!c.isClosed()) {
                c.close();
            }
        }
    }
    //停止查询下载进度
    private void stopQuery() {
        isRuning = false;
        mHandler.removeCallbacks(mQueryProgressRunnable);
    }
    public void setProgressUpdate(DownPresenter.ProgressUpdate update) {
        this.progressUpdate = update;
    }

    //进度更新
    public interface ProgressUpdate {
        void onProgressUpdate(double mDownload_so_far, double mDownload_all);
    }
}
