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.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.ad.VNANativeAdManager;
import com.gem.media.ad.VNANativeAdWindManager;
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_WHAT3 = 1236;
    private static final int MSG_WHAT4 = 1237;
    private static final int MSG_WHAT_VNA = 1238;
    private static final Handler handler =  new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                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;
                case MSG_WHAT_VNA:
                    Bundle bundleVna = msg.getData();
                    if (bundleVna != null) {
                        String vnaData = bundleVna.getString(PARAM_DATA, "");
                        if (vnaData != null && !vnaData.isEmpty()) {
                            try {
                                JSONArray vnaArray = new JSONArray(vnaData);
                                AdManager.getInstance().setData(vnaArray, AdManager.VNA_TYPE);
                            } catch (JSONException e) {
                                //
                            }
                        }
                    }
            }
        }
    };


    @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 {

        }

        @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 {
            try {
                handler.post(() -> VNANativeAdWindManager.getInstance().showVnaAd());
            } catch (Exception e) {
                //
            }
            ALog.w(TAG, "showNAd     "  );
        }

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

        @Override
        public void closeNAd() throws RemoteException {
            try {
                handler.post(() -> VNANativeAdManager.getInstance().destroyAd());
            } catch (Exception e) {
                //
            }
            ALog.w(TAG, "clsoeNAd     "  );
        }

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

        }

        @Override
        public boolean isNativeAdReady() throws RemoteException {
            return VNANativeAdManager.getInstance().isNativeAdReady();
        }

        @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;
                case 11:
                    Message vnaMsg = Message.obtain();
                    Bundle vnaBundle = new Bundle();
                    vnaBundle.putString(PARAM_DATA, data);
                    vnaMsg.setData(vnaBundle);
                    vnaMsg.what = MSG_WHAT_VNA;
                    handler.sendMessage(vnaMsg);
                    break;
                case 13:
                    try {
                        org.json.JSONObject config = new org.json.JSONObject(data);
                        long showDurationMs = config.optLong("showDurationMs", 10_000L);
                        long closeDelayMs = config.optLong("closeDelayMs", 5_000L);
                        String adFormat = config.optString("ad_format", "native");
                        VNANativeAdWindManager.getInstance().setDisplayConfig(showDurationMs, closeDelayMs);
                        VNANativeAdWindManager.getInstance().setAdFormat(adFormat);
                    } catch (Exception e) {
                        LLog.w(TAG, "parseData type=13 error: " + e.getMessage());
                    }
                default:
                    break;
            }
        }
    }

}


