package com.pokkt.papreact.common;

import android.annotation.SuppressLint;

import com.pokkt.PokktAds;
import com.pokkt.sdk.analytics.AnalyticsDetails;
import com.pokkt.sdk.analytics.AnalyticsType;
import com.pokkt.sdk.debugging.Logger;
import com.pokkt.sdk.enums.IAPStoreType;
import com.pokkt.sdk.models.InAppPurchaseDetail;
import com.pokkt.sdk.models.PokktAdViewConfig;
import com.pokkt.sdk.models.PokktUserDetails;

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

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


class Parsers {
    @SafeVarargs
    static String getReturnParamsFromValues(String screenName,
                                            boolean isRewarded,
                                            Map.Entry<String, String>... additionalParams) {
        String params = "";

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("SCREEN_NAME", screenName);
            jsonObject.put("IS_REWARDED", isRewarded);

            if (additionalParams != null) {
                for(Map.Entry<String, String> entry : additionalParams) {
                    jsonObject.put(entry.getKey(), entry.getValue());
                }
            }

            params = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return params;
    }

    static String getJSONStringIGAAssets(Map<String, String> contentMap) {
        try {
            JSONObject jsonObject = new JSONObject();
            for(Map.Entry<String,String> entry : contentMap.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
            return jsonObject.toString();
        } catch (Exception ignored) {

        }
        return null;
    }

    static PokktAdViewConfig getAdViewConfigFromJSONString(String jsonString) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            Logger.printStackTrace(e);
            return null;
        }

        PokktAdViewConfig adPlayerViewConfig = new PokktAdViewConfig();

        adPlayerViewConfig.setShouldAllowSkip(jsonObject.optBoolean("shouldAllowSkip"));
        adPlayerViewConfig.setDefaultSkipTime(jsonObject.optInt("defaultSkipTime"));
        adPlayerViewConfig.setSkipConfirmMessage(jsonObject.optString("skipConfirmMessage"));
        adPlayerViewConfig.setBackButtonDisabled(jsonObject.optBoolean("backButtonDisabled"));
        adPlayerViewConfig.setShouldSkipConfirm(jsonObject.optBoolean("shouldSkipConfirm"));
        adPlayerViewConfig.setAudioEnabled(jsonObject.optBoolean("isAudioEnabled"));
        adPlayerViewConfig.setShouldCollectFeedback(jsonObject.optBoolean("shouldCollectFeedback"));
        adPlayerViewConfig.setSkipConfirmYesLabel(jsonObject.optString("skipConfirmYesLabel"));
        adPlayerViewConfig.setSkipConfirmNoLabel(jsonObject.optString("skipConfirmNoLabel"));
        adPlayerViewConfig.setSkipTimerMessage(jsonObject.optString("skipTimerMessage"));
        adPlayerViewConfig.setIncentiveMessage(jsonObject.optString("incentiveMessage"));
        adPlayerViewConfig.setShouldAllowMute(jsonObject.optBoolean("shouldAllowMute"));

        return adPlayerViewConfig;
    }

    static PokktUserDetails getUserDetailsFromJSONString(String jsonString) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            Logger.printStackTrace(e);
            return null;
        }

        PokktUserDetails userDetails = new PokktUserDetails();

        userDetails.setName(jsonObject.optString("name"));
        userDetails.setAge(jsonObject.optString("age"));
        userDetails.setSex(jsonObject.optString("sex"));
        userDetails.setMobileNumber(jsonObject.optString("mobileNo"));
        userDetails.setEmailAddress(jsonObject.optString("emailAddress"));
        userDetails.setLocation(jsonObject.optString("location"));
        userDetails.setBirthday(jsonObject.optString("birthday"));
        userDetails.setMaritalStatus(jsonObject.optString("maritalStatus"));
        userDetails.setFacebookId(jsonObject.optString("facebookId"));
        userDetails.setTwitterHandle(jsonObject.optString("twitterHandle"));
        userDetails.setEducationInformation(jsonObject.optString("education"));
        userDetails.setNationality(jsonObject.optString("nationality"));
        userDetails.setEmploymentStatus(jsonObject.optString("employment"));
        userDetails.setMaturityRating(jsonObject.optString("maturityRating"));

        return userDetails;
    }

    @SuppressLint("NewApi")
    static AnalyticsDetails getAnalyticsDetailsFromJSONString(String jsonString) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            Logger.printStackTrace(e);
            return null;
        }

        String analyticType = jsonObject.optString("selectedAnalyticsType").isEmpty() ? "NONE" : jsonObject.optString("selectedAnalyticsType");
        Logger.d("[POKKT-JAVA] analyticType: " + analyticType);
        if (analyticType != null && analyticType.isEmpty()) {
            AnalyticsDetails analyticsDetails = new AnalyticsDetails();

            analyticsDetails.setSelectedAnalyticsType(AnalyticsType.valueOf(analyticType));

            analyticsDetails.setGoogleAnalyticsID(jsonObject.optString("googleAnalyticsID"));
            analyticsDetails.setMixPanelProjectToken(jsonObject.optString("mixPanelProjectToken"));
            analyticsDetails.setFlurryApplicationKey(jsonObject.optString("flurryApplicationKey"));

            return analyticsDetails;
        }

        return null;
    }

    static InAppPurchaseDetail getIAPDetailsFromJSONString(String jsonString) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            Logger.printStackTrace(e);
            return null;
        }

        InAppPurchaseDetail detail = new InAppPurchaseDetail();

        detail.setProductId(jsonObject.optString("productId"));
        detail.setPrice(jsonObject.optInt("price"));
        detail.setCurrencyCode(jsonObject.optString("currencyCode"));
        detail.setTitle(jsonObject.optString("title"));
        detail.setDescription(jsonObject.optString("description"));
        detail.setPurchaseData(jsonObject.optString("purchaseData"));
        detail.setPurchaseSignature(jsonObject.optString("purchaseSignature"));
        detail.setPurchaseStore(IAPStoreType.valueOf(jsonObject.optString("purchaseStore")));

        Logger.e("desc: " + detail.getDescription() + " prodId:" + detail.getProductId() + " price:" + 
        		detail.getPrice() + " curCode:" + detail.getCurrencyCode() + " title:" + detail.getTitle() + " purDate:" + 
        		detail.getPurchaseData() + " purStore:" + detail.getPurchaseStore());
        
        return detail;
    }

    static PokktAds.ConsentInfo getConsentInfoFromJSONString(String jsonString) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (JSONException e) {
            Logger.printStackTrace(e);
            return null;
        }

        PokktAds.ConsentInfo info = new PokktAds.ConsentInfo();
        info.setGDPRApplicable(Boolean.parseBoolean(jsonObject.optString("GDPRApplicable", "false")));
        info.setGDPRConsentAvailable(Boolean.parseBoolean(jsonObject.optString("GDPRConsentAvailable", "true")));

        Logger.i("GDPRApplicable: " + info.isGDPRApplicable() + ", GDPRConsentAvailable: " + info.isGDPRConsentAvailable());

        return info;
    }

    static HashMap<String, String> getExtraParamsFromJSONString(String jsonString) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonString);
        } catch (Exception e) {
            Logger.printStackTrace(e);
            return null;
        }

        Iterator<String> itr = jsonObject.keys();
        HashMap<String, String> extraParamsMap = new HashMap<>();
        if (itr != null) {
            while (itr.hasNext()) {
                String key = itr.next();
                extraParamsMap.put(key, jsonObject.optString(key));
            }
        }
        return extraParamsMap;
    }
}
