package com.gem.media.ad;


import static com.gem.media.ad.service.MyDataService.PARAM_ADID;
import static com.gem.media.ad.service.MyDataService.PARAM_AD_TYPE;
import static com.gem.media.ad.service.MyDataService.PARAM_APPID_CHANNELID;
import static com.gem.media.ad.service.MyDataService.PARAM_APPKEY;
import static com.gem.media.ad.service.MyDataService.PARAM_CPID;

import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.ads.cal.picturetranslate.PictureApplication;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.util.ToolUtils;

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

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

public class AdManager {

    private static final class AdManagerHolder {
        static final AdManager adManager = new AdManager();
    }

    public static AdManager getInstance() {
        return AdManagerHolder.adManager;
    }
    private final Map<String, NativeAdClearManager> nativeAdClearManagerHashMap = new HashMap<>(5);

    private boolean canNextAdRequest = true;
    public static final int SERVICE_TYPE = 1;
    public static final int CLEAR_TYPE = 2;
//    private static final Handler handler = new Handler(Looper.getMainLooper());

//    public void loadAllAd() {
//        if (!canNextAdRequest) {
//            return;
//        }
//        handler.postDelayed(runnable, 500);
//    }
//
//    private final Runnable runnable = () -> {
//        InterstitialAdManager.getInstance().loadAd();
//        OpenAdManager.getInstance().loadAd();
//    };

    public void setCanNextAdRequest(boolean canNextAdRequest) {
        this.canNextAdRequest = canNextAdRequest;
        ALog.w("GEM_WZ", "setCanNextAdRequest------>" + canNextAdRequest);
    }

    public boolean isCanNextAdRequest() {
        ALog.w("GEM_WZ", "isCanNextAdRequest------>" + canNextAdRequest);
        return canNextAdRequest;
    }

    public boolean hasCache() {
        return OpenAdManager.getInstance().hasCache() || InterstitialAdManager.getInstance().hasCache();
    }


    public boolean adIsLoading() {
        return OpenAdManager.getInstance().isLoading() || InterstitialAdManager.getInstance().isLoading();
    }
    public void setAllAdExpCount(int count) {
//        Context context = PictureApplication.getApplication();
//        String data = SPreferenceUtils.getString(context, "all");
//        try {
//            JSONObject object;
//            String currentDate = ToolUtils.getCurrentData();
//            if (TextUtils.isEmpty(data)) {
//                object = new JSONObject();
//                object.put("count", count);
//                object.put("date", currentDate);
//                SPreferenceUtils.saveString(context, "all", object.toString(), true);
//            }
//        } catch (Exception e) {
//            ALog.e("AdManager", e.getMessage());
//        }
    }

    private static final Object lock = new Object();
    private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    public void saveAdExpCount() {
        singleThreadExecutor.execute(() -> {
            synchronized (lock) {
                save();
            }
        });
    }


    public void save() {
        ALog.d("AdManager--", "1");
        try {
            Context context = PictureApplication.getApplication();
            if (null == context) {
                return;
            }
            String[] words = context.getPackageName().split("\\.");
            StringBuilder output = new StringBuilder("com.");
            for (String word : words) {
                if (!word.isEmpty()) {
                    output.append(word.charAt(0)); // 提取单词的首字母并添加到输出字符串
                }
            }
            if (TextUtils.isEmpty(output.toString())) {
                ALog.d("AdManager--", "3 pkg is null");
                return;
            }
            ContentResolver contentResolver = context.getContentResolver();
            String data = Settings.Global.getString(contentResolver, output.toString());
            JSONObject object = null;
            String currentDate = ToolUtils.getCurrentData();
            ALog.d("AdManager--", "2 "+data);
            if (!TextUtils.isEmpty(data)) {
                try {
                    object = new JSONObject(data);
                    String date = object.optString("date");
                    int count = object.optInt("count", 0);
                    if (currentDate.equals(date)) {
                        count += 1;
                    } else {
                        count = 1;
                        object.put("date", currentDate);
                    }
                    object.put("count", count);
                } catch (JSONException e) {
                    ALog.e("AdManager--", e.getMessage());
                    Settings.Global.putString(contentResolver, output.toString(), null);
                }
            } else {
                try {
                    object = new JSONObject();
                    object.put("count", 1);
                    object.put("date", currentDate);
                } catch (JSONException e) {
                    ALog.e("AdManager--", e.getMessage());
                }
            }
            if (null != object) {
                ALog.d("AdManager--", "saveAdExpCount " +object+"  output = "+output);
                Settings.Global.putString(context.getContentResolver(), output.toString(), object.toString());
            }
        } catch (Exception e) {
            ALog.e("AdManager--", e.getMessage());
        }
    }

    public void setData(Bundle bundle) {
        String cpId = null;
        String adAppId_channelId = null;
        String adType = null;
        String appKey = null;
        String adId = null;
        try {
            cpId = bundle.getString(PARAM_CPID);
            adAppId_channelId = bundle.getString(PARAM_APPID_CHANNELID);
            adType = bundle.getString(PARAM_AD_TYPE);
            appKey = bundle.getString(PARAM_APPKEY);
            adId = bundle.getString(PARAM_ADID);
        } catch (Throwable e) {
            String er = Log.getStackTraceString(e);
            ALog.w("AdManager--", er);
        }
        if (TextUtils.isEmpty(cpId) || !CpAdData.CP_TOPON.equals(cpId)) {
            return;
        }
        String adAppId = CpAdData.initTopOnAdSdk(adAppId_channelId, appKey);
        AdData adData = CpAdData.getInstance().getAdData(cpId);
        if (adData == null) {
            adData = new AdData();
        }
        adData.setAppId(adAppId);
        adData.addData(adType, adId);
        CpAdData.getInstance().setCpData(cpId, adData);


        //b6509805ed0208
        if (AdData.AD_TYPE_INTERSTITIAL.equals(adType)) {
            InterstitialAdManager.getInstance().loadAd();
        }
        //b1f138leh1o9t5
        if (AdData.AD_TYPE_NATIVE.equals(adType)) {
            NativeAdManager.getInstance().loadAd(adId, 1);
        }
        if (AdData.AD_TYPE_HALF_INTERSTITIAL.equals(adType)) {
            InterstitialHalfAdManager.getInstance().loadAd(adId);
        }
    }

    public void setData(JSONArray array, int type) {
        if (array == null) {
            return;
        }
        for (int i = 0; i < array.length(); i++) {
            JSONObject o = array.optJSONObject(i);
            if (o == null) {
                continue;
            }
            try {
                parseData(o, type);
            } catch (Exception e) {
                //
            }
        }
    }

    private void parseData(JSONObject object, int type) {
        String cpId = null;
        String adAppId_channelId = null;
        String adType = null;
        String appKey = null;
        String adId = null;
        try {
            cpId = object.optString(PARAM_CPID);
            adAppId_channelId = object.optString(PARAM_APPID_CHANNELID);
            adType = object.optString(PARAM_AD_TYPE);
            appKey = object.optString(PARAM_APPKEY);
            adId = object.optString(PARAM_ADID);
        } catch (Throwable e) {
            String er = Log.getStackTraceString(e);
            ALog.w("AdManager--", er);
        }
        if (TextUtils.isEmpty(cpId) || !CpAdData.CP_TOPON.equals(cpId)) {
            return;
        }

        String adAppId = CpAdData.initTopOnAdSdk(adAppId_channelId, appKey);
        AdData adData = CpAdData.getInstance().getAdData(cpId);
        if (adData == null) {
            adData = new AdData();
        }
        adData.setAppId(adAppId);
        adData.addData(adType, adId);
        CpAdData.getInstance().setCpData(cpId, adData);

        //b6509805ed0208
        if (AdData.AD_TYPE_INTERSTITIAL.equals(adType)) {
            InterstitialAdManager.getInstance().loadAd(adId);
        }
        //b1f138leh1o9t5
        if (AdData.AD_TYPE_NATIVE.equals(adType)) {
            if (type == CLEAR_TYPE) {
                if (nativeAdClearManagerHashMap.isEmpty() || nativeAdClearManagerHashMap.get(NativeAdClearManager.P_1) == null) {
                    NativeAdClearManager nativeAdClearManager = new NativeAdClearManager();
                    nativeAdClearManager.setAdPosition(NativeAdClearManager.P_1);
                    nativeAdClearManager.loadAd();
                    nativeAdClearManagerHashMap.put(NativeAdClearManager.P_1, nativeAdClearManager);
                }
            } else if (type == SERVICE_TYPE) {
                NativeAdManager.getInstance().loadAd(adId, 1);
            }
        }
        if (AdData.AD_TYPE_HALF_INTERSTITIAL.equals(adType)) {
            InterstitialHalfAdManager.getInstance().loadAd(adId);
        }
    }



    public NativeAdClearManager getNativeManager(String adPosition) {
        NativeAdClearManager admobNativeManager = nativeAdClearManagerHashMap.get(adPosition);

        if (admobNativeManager == null) {
            admobNativeManager = new NativeAdClearManager();
            admobNativeManager.setAdPosition(adPosition);
            nativeAdClearManagerHashMap.put(adPosition, admobNativeManager);
        }

        return admobNativeManager;
    }

    public NativeAdClearManager searchHasCacheNativeAd() {
        NativeAdClearManager admobNativeManager = null;
        for (NativeAdClearManager manager : nativeAdClearManagerHashMap.values()) {
            if (manager == null) {
                continue;
            }
            if (!manager.isNativeAdReady()) {
                continue;
            }
            admobNativeManager = manager;
            break;
        }
        return admobNativeManager;
    }

}
