//
// Created by KernelTea on 2022/1/6.
//

import Foundation
import AppLovinSDK

public class AdHelper {

    static func toFormatName(_ adFormat: MAAdFormat) -> String {
        switch (adFormat) {
        case MAAdFormat.banner:
            return "BANNER"
        case MAAdFormat.interstitial:
            return "INTERSTITIAL"
        case MAAdFormat.rewarded:
            return "REWARDED"
        case MAAdFormat.mrec:
            return "MREC"
        case MAAdFormat.rewardedInterstitial:
            return "REWARDED_INTERSTITIAL"
        case MAAdFormat.native:
            return "NATIVE"
        case MAAdFormat.leader:
            return "LEADER"
        case MAAdFormat.crossPromo:
            return "CROSS_PROMO"
        default:
            return "UNKNOWN"
        }
    }

    static func toAdPayload(_ ad: MAAd) -> String {

        guard let config = ALSdk.shared()?.configuration else {
            return ""
        }
        let payload: [String: Any] = [
            "ad_platform": "MAX",
            "id": ad.creativeIdentifier ?? "",
            "adunit_id": ad.adUnitIdentifier,
            "adunit_name": ad.placement ?? ad.adUnitIdentifier,
            "adunit_format": toFormatName(ad.format),
            "adgroup_id": "",
            "adgroup_name": "",
            "adgroup_type": "",
            "currency": "USD",
            "country": config.countryCode,
            "app_version": "",
            "publisher_revenue": ad.revenue,
            "network_name": ad.networkName,
            "network_placement_id": ad.networkPlacement,
            "precision": "publisher_defined",
        ]

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted)
            return String(data: jsonData, encoding: .utf8) ?? ""
        } catch {
            print(error.localizedDescription)
        }
        return ""
    }
}