package com.anythink.reactnative.listener;

import com.thinkup.core.api.TUAdInfo;
import com.thinkup.core.api.TUAdMultipleLoadedListener;
import com.thinkup.core.api.TUAdRevenueListener;
import com.thinkup.core.api.TUEventInterface;
import com.thinkup.core.api.TURequestingInfo;
import com.anythink.reactnative.event.ATReactNativeEventEmitter;
import com.anythink.reactnative.utils.BridgeJsonMapUtil;
import com.anythink.reactnative.utils.Const;
import com.anythink.reactnative.utils.MsgTools;
import com.anythink.reactnative.utils.Utils;

import java.util.Map;

/**
* Share Listener factory across ad types: Revenue / MultipleLoaded / AppDownload.
* Each Helper is linked to the corresponding SDK advertising object when it is init.
 */
public final class AdListenerFactory {

    private AdListenerFactory() {
    }

    private static final TUAdRevenueListener REVENUE_LISTENER = new TUAdRevenueListener() {
        @Override
        public void onAdRevenuePaid(TUAdInfo adInfo) {
            String placementId = adInfo != null && adInfo.getPlacementId() != null
                    ? adInfo.getPlacementId() : "";
            MsgTools.printCallback("Common", "AdListenerFactory", "onAdRevenuePaid",
                    "placementId=" + placementId + "--adInfo=" + adInfo);
            ATReactNativeEventEmitter.getInstance().sendCallback(
                    Const.CallbackMethodCall.CommonADCall,
                    Const.CommonADCallBack.AdShowRevenueCallbackKey,
                    placementId, adInfoToMap(adInfo), null, null);
        }
    };

    public static TUAdRevenueListener revenueListener() {
        return REVENUE_LISTENER;
    }

    /** Overseas TPN SDK has no China download listener module; returns null. */
    public static TUEventInterface downloadListener() {
        return null;
    }

    public static TUAdMultipleLoadedListener multipleLoaded(final String callName,
                                                            final String callbackKey,
                                                            final String placementId) {
        return new TUAdMultipleLoadedListener() {
            @Override
            public void onAdMultipleLoaded(TURequestingInfo requestingInfo) {
                MsgTools.printCallback("Common", "AdListenerFactory", "onAdMultipleLoaded",
                        "placementId=" + placementId + "--requestingInfo=" + requestingInfo);
                Map<String, Object> extraDic = BridgeJsonMapUtil.requestingInfoToExtraDic(requestingInfo);
                ATReactNativeEventEmitter.getInstance().sendCallback(
                        callName, callbackKey, placementId, extraDic, null, null);
            }
        };
    }

    private static Map<String, Object> adInfoToMap(TUAdInfo adInfo) {
        if (adInfo == null) {
            return null;
        }
        try {
            return Utils.jsonStrToMap(adInfo.toString());
        } catch (Throwable ignore) {
            return null;
        }
    }
}
