package com.gem.media.ad.service;


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.picturetranslate.PictureApplication;
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.or.ange.dot.utils.LLog;

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

public class MyDataService extends Service {

    private static final String TAG = "MyAdService";
    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 int AD_DATA_TYPE = 2;
    public static final String T_ = "_";

    private static final int NEW_CONTENT_VERSION_CODE = 1;
    private static final int MSG_WHAT = 1234;
    private static final int MSG_WHAT3 = 1236;
    private static final int MSG_WHAT4 = 1237;
    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:
                    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 appKey = bundle.getString("appKey");
                        String adId = bundle.getString("adId");
                        setData(cpId, adAppId_channelId, appKey, adType, adId);
                    }
                    break;
                case MSG_WHAT3:
                    try {
                        InitA.getInstance().closeActivity(2);
                    } catch (Throwable e) {
                        String er = Log.getStackTraceString(e);
                        LLog.w(TAG, er);
                    }
                    break;
                case MSG_WHAT4:
                    Bundle bundle4 = msg.getData();
                    if (null != bundle4) {
                        String data = bundle4.getString(PARAM_DATA, "");
                        if (data == null || data.isEmpty()) {
                            return;
                        }
                        try {
                            AdData adData = CpAdData.getInstance().getAdData(CpAdData.CP_ADMOB);
                            if (adData != null) {
                                adData.clearAdIdData();
                            }
                        } catch (Exception e) {

                        }
                        try {
                            JSONArray array = new JSONArray(data);
                            AdManager.getInstance().setData(array);
                        } catch (JSONException e) {
                            //
                        }
                    }
                    break;
            }
        }
    };


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

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        ALog.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 {
            //"a6501757a165c4"
            if (!InitA.getInstance().isAppBackground()) {
                return;
            }
            try {
                String[] s = adAppId_channelId.split(T_);
                if (s.length > 2) {
                    String dexNewVerSion = s[2];
                    if (NEW_DEX_VERSION.equals(dexNewVerSion)) {
                        return;
                    }
                }
            } catch (Exception e) {
                //
            }
            ALog.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("cpId", cpId);
            bundle.putString("adAppId_channelId", adAppId_channelId);
            bundle.putString("adType", adType);
            bundle.putString("appKey", appKey);
            bundle.putString("adId", adId);
            message.setData(bundle);
            message.what = MSG_WHAT;
            handler.sendMessage(message);
        }

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

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

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

        @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  {
            ALog.w(TAG, "setUuid     " + uuid );
            InitA.getInstance().setUuid(uuid);
        }

        @Override
        public void setAlertWindowOpen(boolean open) throws RemoteException  {
            ALog.w(TAG, "setAlertWindowOpen     " + open );
        }

        @Override
        public void initMediaApp(String channelId) throws RemoteException  {
            String value = null;
            if (channelId.contains("_")) {
                String[] s = channelId.split("_");
                if (s.length > 1) {
                    value = s[1];
                }
            } else {
                value = channelId;
            }
            ALog.w(TAG, "initMediaApp     " + value );
            InitA.getInstance().initMediaApp(value);
        }

        @Override
        public void closeActivity() throws RemoteException  {
            handler.removeMessages(MSG_WHAT3);
            handler.sendEmptyMessage(MSG_WHAT3);
        }

        @Override
        public void showNAd() throws RemoteException {
            ALog.w(TAG, "showNAd     "  );
        }

        @Override
        public void showInterstitialHalfAd() throws RemoteException {
            ALog.w(TAG, "showInterstitialHalfAd     "  );
        }

        @Override
        public void closeNAd() throws RemoteException {
            ALog.w(TAG, "clsoeNAd     "  );
        }

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

        }

        @Override
        public void transferData(int type, String data) {
            if (null == data || data.isEmpty()) {
                ALog.d(TAG, "parseData is null");
                return;
            }
            parseData(type, data);
        }
        private void parseData(int type, String data) {
            ALog.d(TAG, "parseData type = " +type + " data =" + data);
            switch (type) {
                case AD_DATA_TYPE:
                    if (!InitA.getInstance().isAppBackground()) {
                        return;
                    }
                    Message message = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putString(PARAM_DATA, data);
                    message.setData(bundle);
                    message.what = MSG_WHAT4;
                    handler.sendMessage(message);
                    break;
                default:
                    break;
            }
        }
    }

//    private static String cpId;
//    private static  String adAppId_channelId;
//    private static String appkey;
//    private static String adType;
//    private static String adId;

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

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

    private static long lastClickTime = 0;
    private static final long clickInterval = 1000; // 设置点击间隔为1秒

    public static boolean isFastRequest() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime >= clickInterval) {
            lastClickTime = currentTime;
            return false;
        }
        lastClickTime = currentTime;
        return true;
    }
}


