package com.fq.channel.sdk.base.constants;

import android.app.Activity;
import android.content.Context;

import com.fq.channel.sdk.base.utils.Utils;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 描述
 * @Author: FLuty
 * @CreateDate: 2020/4/2 17:27
 */
public class FqConfig {

    public static boolean DEBUG_VERSION = false;

    public static final String KEY_APP_ID = "appId";

    public static final String KEY_CHANNEL_ID = "channelId";

    public static final String KEY_AD_ID = "adId";

    public static final String KEY_AD_FLAG = "adFlag";

    public static final String KEY_CHANNEL_TYPE = "channelType";

    public static final String KEY_UID = "uid";

    public static final String KEY_DEBUG = "isDebug";


    private static final String BASE_URL = "http://ta.funcheergame.com";  //测试环境
//    private static final String BASE_URL = "https://app.funcheergame.com";  //正试环境
//    private static final String BASE_URL = "http://192.168.1.152:9099";  //本地环境

    /**
     * 初始化
     */
    public static String KEY_URL_INT = BASE_URL + "/api/game/v1/active";
    /**
     * 登录
     * api/third/oppo/v1/login
     * api/sdk/channel/v1/login
     */
    public static String KEY_URL_LOGIN = BASE_URL + "/api/third/oppo/v1/login";//
    /**
     * 创建订单
     */
    public static String KEY_URL_CREATE_ORDER = BASE_URL + "/api/sdk/channel/v1/createOrder";


    private String mFilePath = "fq" + "cfg";

    private Map<String, Object> mData = new HashMap<String, Object>();

    private ReentrantLock mLock = new ReentrantLock();

    private static FqConfig sCache;

    private Context mAppContext;

    private String mAppId;
    private String mChannelId;
    private String mAdId;
    private String mAdFlag;

    private FqConfig(Context appContext) {
        mAppContext = appContext;
    }

    public static FqConfig get() {
        if (sCache == null) {
            throw new RuntimeException("get(Context) never called");
        }
        return sCache;
    }

    private static final byte[] SYNC = new byte[0];

    public static FqConfig get(Context cxt) {
        if (sCache == null) {
            synchronized (SYNC) {
                if (sCache == null) {
                    sCache = new FqConfig(cxt.getApplicationContext());
                }
            }
        }
        return sCache;
    }

    public void init(Context appContext) {
        initCfg(appContext);
        Utils.init(appContext);
    }

    public Context getApplicationContext() {
        return mAppContext;
    }

    private void initCfg(Context context) {
        try {
            String st = Utils.readSimplelyFile(context.getAssets().open(mFilePath));
            JSONObject json = new JSONObject(st);
            Iterator<String> it = json.keys();
            while (it.hasNext()) {
                String key = it.next();
                mData.put(key, json.get(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    private WeakReference<Activity> mCurrActivityRef;
    private LinkedList<WeakReference<Activity>> mActivities;

    /**
     * 设置top activity
     *
     * @param activity
     */
    public void setCurrentActivity(Activity activity) {
        if (activity == null) {
            throw new NullPointerException("null passed to setCurrentActivity(Activity)");
        }
        // ----------------保存当前Activity实例---------------//
        if (mCurrActivityRef != null) {
            mCurrActivityRef.clear();
        }
        mCurrActivityRef = new WeakReference<Activity>(activity);
        // ----------------end ----------------//

        // -----------------保存所有开发者设置的Activity--------------------//
        // 用于在退出时，所有activity都退出
        if (mActivities == null) {
            mActivities = new LinkedList<WeakReference<Activity>>();
        }
        mActivities.add(new WeakReference<Activity>(activity));
        // -----------------------end---------------------------//

    }

    /**
     * 获取当前top activity, 依赖于开发者调用，可能返回空
     *
     * @return
     */
    public Activity getCurrentActivity() {
        return mCurrActivityRef != null ? mCurrActivityRef.get() : null;
    }

    public Object get(String key) {
        return mData.get(key);
    }

    public void put(String key, Object value) {
        mLock.lock();
        mData.put(key, value);
        mLock.unlock();
    }

    public void commit() {
        mLock.lock();
        mAppId = (String) mData.get(KEY_APP_ID);
        mChannelId = (String) mData.get(KEY_CHANNEL_ID);
        mAdId = (String) mData.get(KEY_AD_ID);
        mAdFlag = (String) mData.get(KEY_AD_FLAG);
        //正式包 cfg文件不带 "isDebug"字段
        if (mData.get(KEY_DEBUG) != null) {
            DEBUG_VERSION = (Boolean) mData.get(KEY_DEBUG);
        }
        mLock.unlock();
    }

    public String getString(String key) {
        return String.valueOf(mData.get(key));
    }

    /**
     * 获取adId
     * 如果获取不到 则使用默认的adId
     */
    public String getAppId() {
        mLock.lock();
        String key = mAppId;
        mLock.unlock();
        return key;
    }

    /**
     * 获取渠道号 ChannelId
     * 如果获取不到 则使用默认的channelId
     */
    public String getChannelId() {
        mLock.lock();
        String key = mChannelId;
        mLock.unlock();
        return key;
    }

    /**
     * 获取adId
     * 如果获取不到 则使用默认的adId
     */
    public String getAdId() {
        mLock.lock();
        String key = mAdId;
        mLock.unlock();
        return key;
    }

    /**
     * 获取adFlag
     *
     * @return
     */
    public String getAdFlag() {
        mLock.lock();
        String key = mAdFlag;
        mLock.unlock();
        return key;
    }

}
