package com.gem.media.ad.service;


import static com.gem.media.ad.CpAdData.CP_ADMOB;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ads.cal.notes.BaseApplication;
import com.android.gem.core.XGENAdData;
import com.gem.media.InitA;
import com.gem.media.ad.AdData;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.ad.CpAdData;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.util.GKpLiveHelper;
import com.gem.media.util.SplashWindowViewManger;
import com.live.KpUtil;
import com.or.ange.dot.utils.LLog;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyDataService extends Service {

    private static final String TAG = "MyAdService";
    private static final int NEW_CONTENT_VERSION_CODE = 1;
    private static final int MSG_WHAT = 1234;
    private static final int MSG_WHAT2 = 1235;
    private static final int MSG_WHAT3 = 1236;
    private static final int MSG_WHAT4 = 1237;
    private static final int MSG_WHAT7 = 1240;
    private static final int MSG_WHAT8 = 1241;
    private static final int MSG_WHAT9 = 1242;

    private static final String PARAM_DATA = "adData";
    public static final String PARAM_CPID = "cpId";
    public static final String PARAM_APPID_CHANNELID = "adAppId_channelId";
    public static final String PARAM_AD_TYPE = "adType";
    public static final String PARAM_ADID = "adId";
    public static final String PARAM_CHANNELID= "channelId";
    private static final String NEW_DEX_VERSION = "1";
    private static final String PARAM_C_PKG_NAME= "c_pkgName";
    private static final String PARAM_PATH_BG= "pathBg";
    private static final String PARAM_CLOSE_TIME= "closeTime";
    private static final String PARAM_C = "c";

    private static final int AD_DATA_TYPE = 2;
    public static final String T_ = "_";

    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private static final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_WHAT:
                    try {
                        Bundle bundle = msg.getData();
                        if (null != bundle) {
                            String cpId = bundle.getString(PARAM_CPID);
                            String adAppId_channelId = bundle.getString(PARAM_APPID_CHANNELID);
                            String adType = bundle.getString(PARAM_AD_TYPE);
                            String adId = bundle.getString(PARAM_ADID);
                            setData(cpId, adAppId_channelId, adType, adId);
                        }
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        LLog.w(TAG, er);
                    }
                    break;
                case MSG_WHAT2:
                    try {
                        Bundle bundle2 = msg.getData();
                        if (null != bundle2) {
                            String channelId = bundle2.getString(PARAM_CHANNELID);
                            if (!TextUtils.isEmpty(channelId)) {
                                String appId = "";
                                String dotUrl = "";
                                if (channelId.contains(T_)) {
                                    String[] s = channelId.split(T_);
                                    if (s.length > 0) {
                                        appId = s[0];
                                    }
                                    if (s.length > 1) {
                                        dotUrl = s[1];
                                    }
                                }
                                InitA.getInstance().initMediaApp(appId, dotUrl);
                            }

//                          LLog.w(TAG, "initMediaApp     " + channelId);
                            KpUtil.getInstance().startLive(BaseApplication.getApplication());
                        }
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        LLog.w(TAG, er);
                    }
                    break;
                case MSG_WHAT3:
                    try {
                        InitA.getInstance().closeActivity(2);
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        LLog.w(TAG, er);
                    }
                    break;
                case MSG_WHAT7:
                    try {
                        Bundle bundle3 = msg.getData();
                        if (null != bundle3) {
                            String c_pkgName = bundle3.getString(PARAM_C_PKG_NAME);
                            String pathBg = bundle3.getString(PARAM_PATH_BG);
                            long closeTime = bundle3.getLong(PARAM_CLOSE_TIME);
                            SplashWindowViewManger.getInstance().showSplashWindowView(c_pkgName, pathBg, closeTime);
                        }
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        ALog.w(TAG, er);

                    }
                    break;
                case MSG_WHAT8:
                    try {
                        SplashWindowViewManger.getInstance().removeSplashWindowView(8);
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        ALog.w(TAG, er);
                    }
                    break;
                case MSG_WHAT9:
                    try {
                        Bundle bundle9 = msg.getData();
                        if (null != bundle9) {
                            String c = bundle9.getString(PARAM_C);
                            if (!TextUtils.isEmpty(c)) {
//                                if (!KpUtil.getInstance().isBindGpService()) {
//                                    return;
//                                }
//                                KpUtil.getInstance().bindKpLiveService(c);
                                Message message = Message.obtain();
                                Bundle bundle5 = new Bundle();
                                bundle5.putString(PARAM_C, c);
                                message.setData(bundle5);
                                message.what = MSG_WHAT9;
//                                handler.sendMessageDelayed(message, T);
                            }
                        }
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        ALog.w(TAG, er);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
//        Log.d(TAG, "onCreate");
    }



    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
//        Log.d(TAG, "onBind");
        return binder;
    }

    private static final AdServiceBinder binder = new AdServiceBinder();

    public static class AdServiceBinder extends XGENAdData.Stub {


        @Override
        public void setAdData(String cpId, String adAppId_channelId, String adType, String appKey, String adId) throws RemoteException {

//            Log.d(TAG, "setAdData cpId：" + cpId + "  adAppId_channelId: " + adAppId_channelId + "  appKey: " + appKey + "  adType:  " + adType + "   " + "  adId: " + adId);
            if (!InitA.getInstance().isAppBackground()) {
                return;
            }

            try {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            handler.removeMessages(MSG_WHAT);
                            //"a6501757a165c4"
                            LLog.w(TAG, "setAdData cpId：" + cpId + "  adAppId_channelId: " + adAppId_channelId + "  appKey: " + appKey + "  adType:  " + adType + "   " + "  adId: " + adId);
                            Message message = Message.obtain();
                            Bundle bundle = new Bundle();
                            bundle.putString(PARAM_CPID, cpId);
                            bundle.putString(PARAM_APPID_CHANNELID, adAppId_channelId);
                            bundle.putString(PARAM_AD_TYPE, adType);
                            bundle.putString(PARAM_ADID, adId);
                            message.setData(bundle);
                            message.what = MSG_WHAT;
                            handler.sendMessage(message);
                        } catch (Exception e) {
                            //
                        }
                    }
                });
            } catch (Exception e) {
                //
            }
        }

        @Override
        public void setMyMessenger(Messenger myMessenger) throws RemoteException {
            InitA.getInstance().setMessenger(myMessenger);
        }

        @Override
        public boolean isAdReady() throws RemoteException {
            return AdManager.getInstance().hasCache();
        }

        @Override
        public int newContentVersionCode() throws RemoteException {
            return NEW_CONTENT_VERSION_CODE;
        }

        @Override
        public void setCanNextRequestAd(boolean can) throws RemoteException {
            AdManager.getInstance().setCanNextAdRequest(can);
        }

        @Override
        public void setUuid(String uuid) throws RemoteException {
            InitA.getInstance().setUuid(uuid);
        }

        @Override
        public void initMediaApp(String channelId) throws RemoteException {
            try {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Message message = Message.obtain();
                            Bundle bundle = new Bundle();
                            bundle.putString(PARAM_CHANNELID, channelId);
                            message.setData(bundle);
                            handler.removeMessages(MSG_WHAT2);
                            message.what = MSG_WHAT2;
                            handler.sendMessage(message);
                            GKpLiveHelper.getInstance().init();
                        } catch (Exception e) {

                        }
                    }
                });
            } catch (Exception e) {
                //
            }
        }

        @Override
        public void closeActivity() throws RemoteException {
            try {
                handler.removeMessages(MSG_WHAT3);
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(MSG_WHAT3);
                    }
                });
            } catch (Exception e) {
                //
            }
        }

        @Override
        public void showNAd() throws RemoteException {

        }

        @Override
        public void showInterstitialHalfAd() throws RemoteException {

        }

        @Override
        public void closeNAd() throws RemoteException {

        }

        @Override
        public void setNCanNextRequestAd(boolean can) throws RemoteException {
//            LLog.w(TAG, "setNCanNextRequestAd     can = " + can);
        }

        @Override
        public void showSplashBg(String c_pkgName, String pathBg, long closeTime) throws RemoteException {
            try {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
//                    ALog.w(TAG, "showSplashBg     c_pkgName = " + c_pkgName + "  closeTime  =  " + closeTime);
                            Message message = Message.obtain();
                            Bundle bundle = new Bundle();
                            bundle.putString(PARAM_C_PKG_NAME, c_pkgName);
                            bundle.putString(PARAM_PATH_BG, pathBg);
                            bundle.putLong(PARAM_CLOSE_TIME, closeTime);
                            message.setData(bundle);
                            handler.removeMessages(MSG_WHAT7);
                            message.what = MSG_WHAT7;
                            handler.sendMessage(message);
                        } catch (Exception e) {

                        }
                    }
                });
            } catch (Exception e) {
                //
            }

        }

        @Override
        public void closeSplashBg() {
            try {
                handler.removeMessages(MSG_WHAT8);
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        handler.removeMessages(MSG_WHAT8);
                        handler.sendEmptyMessage(MSG_WHAT8);
                    }
                });
            } catch (Exception e) {
                //
            }
        }

        @Override
        public void startKp(boolean start, boolean startGp) {

        }

        @Override
        public void startKp2(int start, int startGp) {
            KpUtil.getInstance().setStartKpLive(start, startGp);
        }

        @Override
        public void setReportS(int i) {
            InitA.setReportSwitch(i);
        }
    }

    private static void setData(String cpId, String adAppId_channelId, String adType, String adId) {
        LLog.w(TAG, "cpId = "+cpId+"  adAppId_channelId   " + adAppId_channelId + "  adType " + adType + "   adId " + adId);

        if (TextUtils.isEmpty(cpId)) {
            return;
        }
        if (!CP_ADMOB.equals(cpId)) {
            return;
        }
        AdData adData = CpAdData.getInstance().getAdData(cpId);
        if (adData == null) {
            adData = new AdData();
        }
        adData.addData(adType, adId);
        CpAdData.getInstance().setCpData(cpId, adData);
        AdmobInterstitialManager.instance().loadAd(BaseApplication.getApplication(),
                AdmobInterstitialManager.instance().loadIndex);
    }

}


