//
//  adopen.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/23.
//

import Foundation
import UIKit
import Alamofire

class NetworkManager {
    static let shared = NetworkManager()
    
    private init() {}
    
    func postRequest(url: String, parameters: [String: Any], headers: HTTPHeaders, completion: @escaping (Result<[String: Any], Error>) -> Void) {
        AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            switch response.result {
            case .success(let value):
                if let json = value as? [String: Any] {
                    completion(.success(json))
                } else {
                    let error = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response format"])
                    completion(.failure(error))
                }
            case .failure(let afError):
                completion(.failure(afError))
            }
        }
    }
}


class AdLoader {
    static let shared = AdLoader()

    private init() {}
    
/// Load
    func loadAds( idfa: String?, adId: String, btnPositionX: CGFloat, btnPositionY: CGFloat, ecpm: Float?, completion: @escaping (Result<Int, Error>) -> Void) {
            let parameters: [String: Any] = [
                "appid": "com.countdown.day.daycount",
                "idfa": idfa ?? "",
                "ads": [
                    [
                        "id": adId,
                        "btn_position": [
                            "x": btnPositionX,
                            "y": btnPositionY
                        ],
                        "ecpm": ecpm ?? ""
                    ]
                ]
            ]

        NetworkManager.shared.postRequest(url: StartManager.shared.loadurl, parameters: parameters, headers: StartManager.shared.headers) { result in
                switch result {
                case .success(let data):
                    if let status = data["status"] as? String, status == "Success" {
                        if let needLoad = data["needload"] as? Int {
                            completion(.success(needLoad))
                            return
                        }
                    }
                    let error = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response format"])
                    completion(.failure(error))
                case .failure(let error):
                    completion(.failure(error))
                }
            }
        }
    
//    closd
    func closeAd( idfa: String?, adId: String, completion: @escaping (Result<[String: Any], Error>) -> Void) {
         let parameters: [String: Any] = [
             "appid": "com.countdown.day.daycount",
             "idfa": idfa ?? "",
             "id": adId
         ]

         NetworkManager.shared.postRequest(url: StartManager.shared.closedUrl, parameters: parameters, headers: StartManager.shared.headers) { result in
             completion(result)
         }
     }
    
//    show
    func showAd(idfa: String?, adId: String, ecpm: Float?,ad:Bool, completion: @escaping (Result<Int, Error>) -> Void) {
            let parameters: [String: Any] = [
                "appid": "com.countdown.day.daycount",
                "idfa": idfa ?? "",
                "id": adId,
                "ecpm": ecpm ?? "",
                "ad":ad
            ]

            NetworkManager.shared.postRequest(url:StartManager.shared.showurl , parameters: parameters, headers: StartManager.shared.headers) { result in
                switch result {
                case .success(let data):
                    print("Response:--- \(data)")
                    if let status = data["status"] as? String, status == "Success" {
                        if let closeTime = data["close"] as? Int {
                            completion(.success(closeTime))
                            let seconds = millisecondsToSeconds(milliseconds: closeTime)
                            DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
                                closeADWindow()
                            }
                            return
                        }
                    }
                    let error = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response format"])
                    completion(.failure(error))
                case .failure(let error):
                    completion(.failure(error))
                }
            }
        }
    
    
}



///毫秒转秒
func millisecondsToSeconds(milliseconds: Int) -> Double {
    
    return Double(milliseconds) / 1000.0
    
}


///Widows
func closeADWindow() {
    if let keyWindow = UIApplication.shared.keyWindow {
        for subview in keyWindow.subviews {
            if let vc = subview.subviews.first?.next as? UIViewController{
                
                if String(describing: type(of: vc)) == "ALAppLovinVideoViewController" {
                    let selector = NSSelectorFromString("handleCloseButton")
                    if vc.responds(to: selector) {
                        vc.perform(selector)
                    }
                }
                else if String(describing: type(of: vc)) == "ALVASTVideoViewController" {
                    let selector = NSSelectorFromString("dismiss")
                    if vc.responds(to: selector) {
                        vc.perform(selector)
                    }
                }
               
            }
        }
    }
}
