//
//  PlayRootManager.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/13.
//

//import ADManager
import Foundation
import KLTips
import TSVideoKit

struct SleepModel: Codable {
    var isOpen: Bool = false
    var countTime: TimeInterval = 0
}

extension LoopMode {
    var icon: String {
        switch self {
        case .cyclic:
            return "ic_cycle"
        case .random:
            return "ic_shuffle"
        case .repeat:
            return "ic_single"
        }
    }
}

class PlayerManager {
    static let shared: PlayerManager = .init()
    @Published var sleepModel: SleepModel = .init()
    var showedPlayAd: Bool = false

    var selectedVideos: [TSVideo] = []
    var removePlaylist: TSPlayList?

    var currentLoopMode: LoopMode {
        player?.playControl.viewModel.loopMode ?? .cyclic
    }

    var rootVc: TSTabBarController? {
        if let vc = UIApplication.shared.windows.first?.rootViewController as? TSTabBarController {
            return vc
        }
        return nil
    }

    var miniBar: PlayMiniBar {
        if let vc = UIApplication.shared.windows.first?.rootViewController as? TSTabBarController {
            return vc.miniBar
        }
        return .init()
    }

    var player: PlayDetailViewController? {
        if let vc = UIApplication.shared.windows.first?.rootViewController as? TSTabBarController {
            return vc.playerVc
        }
        return nil
    }

    var currentVideo: TSVideo? {
        player?.playControl.viewModel.currentVideo
    }

    func hiddePlayerViewController() {
        if let tabVc = UIApplication.shared.windows.first?.rootViewController as? TSTabBarController {
            tabVc.hidePlayerVc()
        }
    }

    func showPlayerViewController() {
        if let tabVc = UIApplication.shared.windows.first?.rootViewController as? TSTabBarController {
            tabVc.showPlayerVc()
        }
    }

    func playOrPause() {
        guard let player = player else {
            return
        }
        /// 非vip且非国区，暂停要出广告
        if !PurchaseManager.default.isVip,
           player.playControl.player.isPlaying,
           let rootVc = rootVc {
            rootVc.presentingViewController?.dismiss(animated: false)
//            ADManager.shared.showAd(scene: ADScene.pauseInsert, from: rootVc)
        }
        player.playControl.pauseOrPlay()
    }

    func pause() {
        player?.playControl.pause()
    }

    func play() {
        player?.playControl.play()
    }

    func nextPlayModel() {
        player?.playControl.viewModel.loopMode = player?.playControl.viewModel.loopMode.nextMode() ?? .cyclic
    }

    func playNext() {
        if FitManager.isAr {
            player?.playControl.playLast()
        } else {
            player?.playControl.playNext()
        }
    }

    func playLast() {
        if FitManager.isAr {
            player?.playControl.playNext()
        } else {
            player?.playControl.playLast()
        }
    }

    func playVideo(video: TSVideo, list: [TSVideo], scene: TSPlayScene, onceAdKey: String) {
//        if let vc = rootVc, !PurchaseManager.default.isVip {
//            ADManager.shared.showAd(scene: ADScene.playInsert, from: vc) { state in
//                if state == .finished || state == .fail {
//                    self.showPlayerViewController()
//                    self.player?.playControl.playVideo(video: video, list: list, scene: scene)
//                }
//            }
//        } else {
            showPlayerViewController()
            player?.playControl.playVideo(video: video, list: list, scene: scene)
//        }
    }

    func playVideo(onlineVideo: VideoOnlineModel, recommendDatas: [VideoOnlineModel], scene: TSPlayScene) {
        showPlayerViewController()
        player?.playControl.playOnlineVideo(video: onlineVideo, recommendDaras: recommendDatas, scene: scene)
    }

    func showMutiOperateView(isFromPlaylist: Bool, playlist: TSPlayList? = nil) {
//        rootVc?.showMultiSelectView()
    }

    func hideMutiOperateView() {
//        rootVc?.hideMultiSelectView()
    }

    @objc func addVideosToPlaylist() {
        if selectedVideos.isEmpty {
            return
        }
        let vc = AddPlayListViewController(videos: selectedVideos)
        vc.addSuccessBlock = {
//            KLTips.showAutoHidden("Added Successfully".localized())
            THUD.toast("Added Successfully".localized())
            PlayerManager.shared.hideMutiOperateView()
            /// 发送刷新通知
            NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
        }
        PlayerManager.shared.rootVc?.present(vc, animated: true)
    }

    @objc func deleteSelectedVideos() {
        if selectedVideos.isEmpty {
            return
        }

        let ac = UIAlertController(title: nil,
                                   message: "Are you sure to delete".localized(), preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel))
        ac.addAction(UIAlertAction(title: "Delete".localized(), style: .destructive, handler: { _ in

            /// 删除当前歌曲
            if self.selectedVideos.contains(where: {
                $0.videoId == TSVideoOperator.shared.playerViewModel.currentVideo?.videoId
            }) {
                TSVideoOperator.shared.playerController.player.stop()
                TSVideoOperator.shared.playerViewModel.currentVideo = nil
            }

            /// 删除播放列表歌曲
            let videoIds: [String] = self.selectedVideos.compactMap {
                $0.videoId
            }

            TSVideoOperator.shared.dataManager.deleteVideos(videos: self.selectedVideos) { _ in

                PlayerManager.shared.hideMutiOperateView()

                for item in videoIds {
                    TSVideoOperator.shared.playerViewModel.currentVideos.removeAll { $0.isFault }
                }
                // 播放删完列表后的第一首
                let newVideos = TSVideoOperator.shared.playerViewModel.currentVideos
                if let video = newVideos.first {
                    /// 播放的时候回刷新列表不用重复刷
                    TSVideoOperator.shared.playerController.playVideo(video: video, list: newVideos, scene: .local)
                    /// 发送刷新通知
                    NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                } else {
                    /// 发送刷新通知
                    NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                }
            }

        }))
        PlayerManager.shared.rootVc?.present(ac, animated: true)
    }
}
