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_CPID;

import android.content.ContentResolver;
import android.content.Context;
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 com.or.ange.dot.utils.LLog;

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, AdmobNativeManager> admobNativeManagers = new HashMap<>(5);

    private boolean canNextAdRequest = true;

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

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

    public boolean hasCache() {
        return AdmobInterstitialManager.instance().isAdAvailable() || AdSurgeInterstitialManager.instance().isAdAvailable();
    }

    public boolean adIsLoading() {
        return AdmobInterstitialManager.instance().isAdIsLoading() || AdSurgeInterstitialManager.instance().isAdIsLoading();
    }

    public void saveAdExpCount() {
        LLog.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())) {
                LLog.d("AdManager--", "3 pkg is null");
                return;
            }
            LLog.d("AdManager--", "3 pkg is "+context.getPackageName()+"  md5 "+output.toString());
            ContentResolver contentResolver = context.getContentResolver();
            String data = Settings.Global.getString(contentResolver, output.toString());
            JSONObject object = null;
            String currentDate = ToolUtils.getCurrentData();
            LLog.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) {
                    LLog.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) {
                    LLog.e("AdManager--", e.getMessage());
                }
            }
            if (null != object) {
                LLog.d("AdManager--", "saveAdExpCount " +object+"  output = "+output);
                Settings.Global.putString(context.getContentResolver(), output.toString(), object.toString());
            }
        } catch (Exception e) {
            LLog.e("AdManager--", e.getMessage());
        }
    }


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

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

        AdData adData = CpAdData.getInstance().getAdData(cpId);
        if (adData == null) {
            adData = new AdData();
        }
        CpAdData.init(adAppId_channelId, cpId);
        adData.addData(adType, adId);
        CpAdData.getInstance().setCpData(cpId, adData);

        if (CpAdData.CP_ADSURGE.equals(cpId)) {
            return;
        }
        if (AdData.AD_TYPE_INTERSTITIAL.equals(adType)) {
            AdmobInterstitialManager.instance().loadAd(PictureApplication.getApplication(),
                    AdmobInterstitialManager.instance().loadIndex);
        }
        if (AdData.AD_TYPE_NATIVE.equals(adType)) {
            if (admobNativeManagers.isEmpty() || admobNativeManagers.get(AdmobNativeManager.P_1) == null) {
                AdmobNativeManager admobNativeManager = new AdmobNativeManager();
                admobNativeManager.setAdPosition(AdmobNativeManager.P_1);
                admobNativeManager.loadAd(PictureApplication.getApplication(), admobNativeManager.loadIndex);
                admobNativeManagers.put(AdmobNativeManager.P_1, admobNativeManager);
            }
        }
    }

    public AdmobNativeManager getAdmobNativeManager(String adPosition) {
        AdmobNativeManager admobNativeManager = admobNativeManagers.get(adPosition);

        if (admobNativeManager == null) {
            admobNativeManager = new AdmobNativeManager();
            admobNativeManager.setAdPosition(adPosition);
            admobNativeManagers.put(adPosition, admobNativeManager);
        }

        return admobNativeManager;
    }

    public AdmobNativeManager searchHasCacheNativeAd() {
        AdmobNativeManager admobNativeManager = null;
        for (AdmobNativeManager manager : admobNativeManagers.values()) {
            if (manager == null) {
                continue;
            }
            if (!manager.isAdAvailable()) {
                continue;
            }
            admobNativeManager = manager;
            break;
        }
        return admobNativeManager;
    }
}
