package com.ym.library.utils;

import android.app.DownloadManager;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.ym.library.module.NewsEntity;
import com.ym.library.net.AdUpload;
import com.ym.modulecommon.AppliContext;


/**
 * Created by gaoleichao on 2019-09-05
 */
public class ZxDownLoadServices extends IntentService {

    private static final String ACTION_FOO = "ACTION_FETCH_NEW_ITEMS";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "PARAM";


    public ZxDownLoadServices() {
        super("ZxDownLoadServices");
    }

    public static void startActionFoo(Context context, NewsEntity param1) {
        Intent intent = new Intent(context, ZxDownLoadServices.class);
        intent.setAction(ACTION_FOO);
        if (!param1.isDowanloaded()) {
            param1.setDowanloaded(true);
            intent.putExtra(EXTRA_PARAM1, param1);
//            Utils.showToast(AppContext.getAppContext(),"开始下载");
        } else {
            NewsEntity data = new NewsEntity();
            data.setUrl(param1.getUrl());
            intent.putExtra(EXTRA_PARAM1, data);
        }
        context.startService(intent);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final NewsEntity param1 = (NewsEntity) intent.getSerializableExtra(EXTRA_PARAM1);
                handleActionFoo(param1);
            }
        }
    }

    private void handleActionFoo(NewsEntity param1) {
        // TODO: Handle action Foo
        downloadAPK(param1);
    }

    DownloadManager downloadManager;


    //使用系统下载器下载
    private void downloadAPK(NewsEntity data) {
        String versionUrl = data.getUrl();
        //注册广播接收者，监听下载状态
//        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        int last = versionUrl.lastIndexOf("/") + 1;
        String apkName = versionUrl.substring(last);
        if (!apkName.contains(".apk")) {
            if (apkName.length() > 10) {
                apkName = apkName.substring(apkName.length() - 10);
            }
            apkName += ".apk";
        }
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(false);//漫游网络是否可以下载

        //设置文件类型，可以在下载结束后自动打开该文件
//        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
//        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
        request.setMimeType("application/vnd.android.package-archive");

        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);

        //sdcard的目录下的download文件夹，必须设置
//        request.setDestinationInExternalPublicDir("/com.cloud.juan/dowanload/", apkName);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);//也可以自己制定下载路径

        //将下载请求加入下载队列
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        AdUpload.INSTANCE.onDownloadStart(data);
        //加入下载队列后会给该任务返回一个long型的id，
        //通过该id可以取消任务，重启任务等等，看上面源码中框起来的方法
        long mTaskId = downloadManager.enqueue(request);
        EventUtils.INSTANCE.onEvent("download_start", data.getUrl());
        listener(mTaskId, data);
    }

    private boolean flag = true;

    private void listener(long ID, NewsEntity data) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(ID);
        Log.d("ZxDownLoadServices", "id:" + ID);
        flag = true;
        while (flag) {
            synchronized (this) {
                Cursor c = downloadManager.query(query);
                if (c != null && c.moveToFirst()) {
                    int status = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                    Log.d("ZxDownLoadServices", "status:" + status);
                    switch (status) {
                        case DownloadManager.STATUS_SUCCESSFUL:
                            flag = false;
                            AdUpload.INSTANCE.onDownloadEnd(data);
                            OpenFiles.INSTANCE.openFile(PhoneUtils.INSTANCE.getRealFilePath(AppliContext.get(), downloadManager.getUriForDownloadedFile(ID)));
                            Log.d("ZxDownLoadServices", "STATUS_SUCCESSFUL");
                            AdUpload.INSTANCE.onInstallStart(data);
//                            InstalledUtils.INSTANCE.addData(data);
                            EventUtils.INSTANCE.onEvent("download_end", data.getUrl());
                            EventUtils.INSTANCE.onEvent("install_start", data.getUrl());
                            break;
                        case DownloadManager.STATUS_PAUSED:
                            Log.d("ZxDownLoadServices", "STATUS_PAUSED");
                            break;
                        case DownloadManager.STATUS_RUNNING:
                            Log.d("ZxDownLoadServices", "STATUS_RUNNING");
                            break;
                        case DownloadManager.STATUS_PENDING:
                            Log.d("ZxDownLoadServices", "STATUS_PENDING");
                            break;
                        case DownloadManager.STATUS_FAILED:
                            flag = false;
                            Log.d("ZxDownLoadServices", "STATUS_FAILED");
                            break;
                    }
                } else {
                    flag = false;
                }
                if (c != null) {
                    c.close();
                }
                try {
                    wait(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.v("ZxDownLoadServices", "耗时任务执行完成");
    }

}
