//
//  ADLoadingViewController.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/25.
//

import UIKit
import ADManager

class ADLoadingViewController: BasePresentViewController {
    var adScene: ADScene = .unknow
    var finishedHandler: ((Bool) -> Void)?

    private let totalDuration: TimeInterval = 10
    private var remindTimeInterval: TimeInterval = 0
    private var loadCompletionHandler: ADCompletionHandler?

    // 定时器
    private var timer: DispatchSourceTimer?
    override func viewDidLoad() {
        super.viewDidLoad()

        loadCompletionHandler = { [weak self] state in
            guard let self = self else { return }

            switch state {
            case .willPresent:
                THUD.hide()
            case .finished:
                let finishedHandler = self.finishedHandler
                finishedHandler?(true)
            case .fail:
                self.stopTimer()
                self.updateLoadingState(.failure)
            case .loadSuccess:
                self.stopTimer()
                // 加载成功，且未超过计时，显示，超时则本次不展示
                if remindTimeInterval > 0 {
                    self.view.backgroundColor = .clear
                    self.dismiss(animated: false) {
                        if let vc = PlayerManager.shared.rootVc {
                            vc.presentingViewController?.dismiss(animated: false)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                                ADManager.shared.showAd(scene: self.adScene, from: vc) { state in
                                    switch state {
                                    case .willPresent:
                                        THUD.hide()
                                    case .finished:
                                        let finishedHandler = self.finishedHandler
                                        finishedHandler?(true)
                                    case .fail:
                                        self.stopTimer()
                                        self.updateLoadingState(.failure)
                                    case .loadSuccess:
                                        self.stopTimer()
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.startLoadAD()
        }
    }

    override var shouldDismissWhenTapBackground: Bool {
        return false
    }

    override var alertBackgroundColor: UIColor {
        return .clear
    }

    func startLoadAD() {
        updateLoadingState(.loading)
        startTimer()

        ADManager.shared.requestAd(for: adScene, completionHandler: loadCompletionHandler)
    }

    private func startTimer() {
        remindTimeInterval = totalDuration
        if timer == nil {
            print("===剩余：\(remindTimeInterval)")
            timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
            timer?.schedule(deadline: .now(), repeating: .milliseconds(200))
            timer?.setEventHandler { [weak self] in
                guard let self = self else { return }
                self.remindTimeInterval -= 0.2
                print("===剩余：\(self.remindTimeInterval)")
                if self.remindTimeInterval <= 0 {
                    self.stopTimer()
                    DispatchQueue.main.async {
                        self.updateLoadingState(.failure)
                    }
                }
            }
            timer?.resume()
        }
    }

    func stopTimer() {
        timer?.cancel()
        timer = nil
    }

    enum State {
        case loading
        case failure
    }

    func updateLoadingState(_ state: State) {
        switch state {
        case .loading:
            THUD.showLoading("Unlocking...".localized(), message: "It will be unlocked after an ad.".localized())
        case .failure:
            THUD.showLoading(UIImage(named: "img-pre-ad-emo-error"), message: "Loading Failed".localized()) { [weak self] isClose in
                THUD.hide()
                if isClose {
                    self?.dismiss(animated: false) {
                        self?.finishedHandler?(false)
                    }
                } else {
                    self?.startLoadAD()
                }
            }
        }
    }

    deinit {
        print("===deinit: \(Self.description())")
    }
}
