package com.uiui.zyappstore.push;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.text.TextUtils;

import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uiui.zyappstore.disklrucache.CacheHelper;
import com.uiui.zyappstore.utils.FileUtils;
import com.uiui.zyappstore.utils.JGYUtils;
import com.uiui.zyappstore.utils.ToastUtil;

import java.io.File;
import java.util.List;

public class PushManager {
    private static final String TAG = PushManager.class.getSimpleName();

    @SuppressLint("StaticFieldLeak")
    private static PushManager sInstance;
    private Context mContext;
    private ContentResolver mResolver;
    private CacheHelper mCacheHelper;

    private PushManager(Context context) {
        if (context == null) {
            throw new RuntimeException("Context is NULL");
        }
        this.mContext = context;
        this.mResolver = context.getContentResolver();
        this.mCacheHelper = new CacheHelper(context);
    }

    public static void init(Context context) {
        if (sInstance == null) {
            sInstance = new PushManager(context);
        }
    }

    public static PushManager getInstance() {
        if (sInstance == null) {
            throw new IllegalStateException("You must be init PushManager first");
        }
        return sInstance;
    }

    // 9.强制安装应用
    private static final String ACTION_FORCE_INSTALLAPK = "9";

    public void setPushContent(String title, String extras) {
        switch (title) {
            case ACTION_FORCE_INSTALLAPK:
                forceInstallApk( extras);
                break;
            default:
        }
    }

    private void forceInstallApk(String jsonString) {
        if (TextUtils.isEmpty(jsonString)) {
            return;
        }
        JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
        final String packages = jsonObject.get("package").getAsString();
        ToastUtil.debugShow("收到应用安装消息：包名" + packages);
        String url = jsonObject.get("url").getAsString();
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (Aria.download(this).taskExists(url)) {
            List<DownloadEntity> entity = Aria.download(this).getDownloadEntity(url);
            for (DownloadEntity downloadEntity : entity) {
                Aria.download(this).load(downloadEntity.getId()).cancel(true);
            }
        }
        File file = new File(JGYUtils.getInstance().getDownLoadPath());
        file.mkdirs();
        FileUtils.ariaDownload(mContext, url, jsonObject);
        Aria.download(this).resumeAllTask();
    }
}
