package com.mjsheng.myappstore.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.util.Log;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mjsheng.myappstore.base.MyApplication;
import com.mjsheng.myappstore.bean.AppData;
import com.mjsheng.myappstore.bean.UploadAppInfo;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.UploadAppInfoApi;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.Utils;

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

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class NewAppReceiver extends BroadcastReceiver {

    private static final String TAG = "--NewAppReceiver--";
    private String action = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        action = intent.getAction();
        //接收安装广播
        if (action.equals(Intent.ACTION_PACKAGE_ADDED) || action.equals(Intent.ACTION_PACKAGE_REPLACED)) {
            Intent allIntent = new Intent();
            allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
            context.sendBroadcast(allIntent);
            String packageName = intent.getDataString().replace("package:", "");
            ApkUtils.removeInfo(packageName);
            Log.e(TAG, "安装了:" + packageName + "包名的程序");
            Log.e("fht", "安装了:" + packageName + "包名的程序");
            OkGo.post(Configure.HTTP_TAG_DOWNLOAD_URL)
                                .params("key", Configure.HTTP_KEY)
                                .params("sn", Utils.getSerial())
                                .params("package", packageName)
                                .tag(this)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {

                                    }
                                });
            SaveListUtils.getDownLoadList().remove(packageName);//移除下载列表
//            ToastTool.show("安装成功");
            if (!packageName.equals(Utils.YOUNGSYSTEM_APP_TONGBU) && !packageName.equals(context.getPackageName())){
                updateUserApp(context,packageName);
            }
            //  下载管理服务 删除对应任务
            Intent msgIntent = new Intent(Utils.DOWNLOAD_DELETE_PACKAGENAME_ACTION);
            msgIntent.putExtra("packageName", packageName);
            context.sendBroadcast(msgIntent);

            Intent intent1 = new Intent();
            if (action.equals(Intent.ACTION_PACKAGE_ADDED)){
                intent1.setAction(Utils.ACTION_PACKAGE_ADDED);
            }else {
                intent1.setAction(Utils.ACTION_PACKAGE_REPLACED);
            }
            intent1.putExtra("packageName", packageName);
            context.sendBroadcast(intent1);
            getAppInfo(context);
        }
        //接收卸载广播
        if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) {
            String packageName = intent.getDataString().replace("package:", "");
            Log.e(TAG, "卸载了:" + packageName + "包名的程序");

            if (!packageName.equals(Utils.YOUNGSYSTEM_APP_TONGBU) && !packageName.equals(context.getPackageName())){
                deletedateUserApp(context,packageName);
            }
            Intent intent1 = new Intent();
                intent1.setAction(Utils.ACTION_PACKAGE_REMOVED);
            intent1.putExtra("packageName", packageName);
            context.sendBroadcast(intent1);
            getAppInfo(context);
        }
    }


    private void deletedateUserApp(Context context, String packageName) {
        String category = AppData.getConfigApp(context, packageName);
        if (category != null && category.toString() != "") {
            AppData.deleteAppsByAppKey(context, packageName);
            //  子界面下载回调 提示更新UI
            Intent intent = new Intent();
            intent.setAction(Utils.DOWNLOADAPP_CALLBACK);
            intent.putExtra("data", category);
            context.sendBroadcast(intent);
        }
    }

    private void updateUserApp(Context context, String packageName) {
        String[] category = AppData.getDownloadApp(context, packageName);
        if (category != null && category.toString() != "") {
            AppData.updateConfigApp(context, category[0], category[1], packageName);
            AppData.deleteDownloadApp(context, packageName);
            //  子界面下载回调 提示更新UI
            Intent intent = new Intent();
            intent.setAction(Utils.DOWNLOADAPP_CALLBACK);
            intent.putExtra("data", category[0]);
            context.sendBroadcast(intent);
        }
    }

    private void getAppInfo(Context context) {
        ArrayList<UploadAppInfo> appList = new ArrayList<UploadAppInfo>(); //用来存储获取的应用信息数据
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);

        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            UploadAppInfo uploadAppInfo = new UploadAppInfo();
            uploadAppInfo.setApp_name(packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString());
            uploadAppInfo.setPackage_name(packageInfo.packageName);
            uploadAppInfo.setId(i);
            String firstInstallTime = Utils.transferLongToDate(packageInfo.firstInstallTime);
            uploadAppInfo.setInstall_time(firstInstallTime);


            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                //非系统应用
                appList.add(uploadAppInfo);
            } else {

            }


        }

//        Log.e("mjsheng", "UploadAppInfo========" + appList.toString());

        Gson gson = new Gson();
        String jsonString = gson.toJson(appList);
//        Log.e("mjsheng", "json========" + jsonString);

        UploadAppInfoApi uploadAppInfoApi = Network.getUploadAppInfoApi();
        uploadAppInfoApi.getUploadAppInfoApi(Configure.HTTP_KEY, Utils.getSerial(), jsonString)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Log.e("mjhseng", "上传的结果"+responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "UploadAppInfoApi=onError:");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
