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.notes.BaseApplication;
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 {
    public static final int VNA_TYPE = 3;

    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;
        ALog.w("GEM_WZ", "setCanNextAdRequest------>" + canNextAdRequest);
    }

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

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

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

    public void saveAdExpCount() {
        ALog.d("AdManager--", "1");
        try {
            Context context = BaseApplication.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;
            }
            ALog.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();
            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());
        }
    }
    /**
     * VNA 专用 setData：直接写入 CpAdData，不触发旧 native 加载，
     * 然后调用 VNANativeAdManager.loadVnaAd()。
     */
    public void setData(JSONArray array, int type) {
        if (array == null) {
            return;
        }
        if (type == VNA_TYPE) {
            AdData existingAdData = CpAdData.getInstance().getAdData(CpAdData.CP_ADMOB);
            if (existingAdData != null && existingAdData.mapHashMap != null) {
                existingAdData.mapHashMap.remove(AdData.AD_TYPE_NATIVE);
            }
            for (int i = 0; i < array.length(); i++) {
                JSONObject o = array.optJSONObject(i);
                if (o == null) {
                    continue;
                }
                try {
                    String cpId = o.optString(PARAM_CPID);
                    String adAppId_channelId = o.optString(PARAM_APPID_CHANNELID);
                    String adType = o.optString(PARAM_AD_TYPE);
                    String adId = o.optString(PARAM_ADID);
                    if (TextUtils.isEmpty(cpId) || !CpAdData.CP_ADMOB.equals(cpId)) {
                        continue;
                    }
                    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);
                } catch (Exception e) {
                    ALog.w("AdManager--", "setData VNA error: " + e.getMessage());
                }
            }
            VNANativeAdManager.getInstance().loadVnaAd();
        } else {
            setData(array);
        }
    }

    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);
            ALog.w("AdManager--", er);
        }
        if (TextUtils.isEmpty(cpId) || !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);
        if (AdData.AD_TYPE_INTERSTITIAL.equals(adType)) {
            AdmobInterstitialManager.instance().loadAd(BaseApplication.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(BaseApplication.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;
    }
}
