//
//  RCTConvert+Shopping.swift
//  react-native-firework-sdk
//
//  Created by Jeff Zheng on 2021/12/31.
//

import Foundation

extension RCTConvert {
    static func buildProducts(_ rawProducts: [AnyObject]?) -> [Product]? {
        guard let rRawProducts = rawProducts else {
            return nil
        }

        var products = [Product]()
        for rawProduct in rRawProducts {
            let product = buildProduct(rawProduct as? [String: Any])
            if let rProduct = product {
                products.append(rProduct)
            }
        }
        return products
    }

    static func buildProduct(_ product: [String: Any]?) -> Product? {
        guard let rProduct = product else {
            return nil
        }

        let jsonData = try? JSONSerialization.data(
            withJSONObject: rProduct, options: .prettyPrinted)
        guard let rJsonData = jsonData else {
            return nil
        }

        var result: Product?
        do {
            result = try JSONDecoder().decode(Product.self, from: rJsonData)
        } catch let error {
            print(error.localizedDescription)
        }
        return result
    }

    static func buildProductInfoViewConfiguration(_ config: [String: Any]?)
        -> ProductInfoViewConfiguration? {
        guard let rConfig = config else {
            return nil
        }

        let jsonData = try? JSONSerialization.data(withJSONObject: rConfig, options: .prettyPrinted)
        guard let rJsonData = jsonData else {
            return nil
        }

        var result: ProductInfoViewConfiguration?
        do {
            result = try JSONDecoder().decode(ProductInfoViewConfiguration.self, from: rJsonData)
        } catch let error {
            print(error.localizedDescription)
        }

        return result
    }

    static func buildShoppingCTAResult(_ result: [String: Any]?)
        -> ShoppingCTAResult? {
        guard let rResult = result else {
            return nil
        }

        let jsonData = try? JSONSerialization.data(withJSONObject: rResult, options: .prettyPrinted)
        guard let rJsonData = jsonData else {
            return nil
        }

        var ctaResult: ShoppingCTAResult?
        do {
            ctaResult = try JSONDecoder().decode(ShoppingCTAResult.self, from: rJsonData)
        } catch let error {
            print(error.localizedDescription)
        }

        return ctaResult
    }
}
