//
//  CWOperateViewController+Ext.swift
//  ColorfulWallpaper
//
//  Created by ni on 2024/9/19.
//

import Foundation
import KLTips
import TSVideoKit

extension CWOperateViewController {
    func addTargets() {
        disAppearArea.addTarget(self, action: #selector(dismissCurrentVc), for: .touchUpInside)
        likeItem.addTarget(self, action: #selector(likeVideoAction(sender:)), for: .touchUpInside)
        addPlaylistItem.addTarget(self, action: #selector(addToPlayList), for: .touchUpInside)
        shareItem.addTarget(self, action: #selector(shareApp), for: .touchUpInside)
        deleteItem.addTarget(self, action: #selector(deleteVideoAction), for: .touchUpInside)
        removeFromPlaylist.addTarget(self, action: #selector(removeSongFromPlaylist), for: .touchUpInside)
    }

    @objc func likeVideoAction(sender: CWOperateItemView) {
        dismiss(animated: true) {
            if let mVideo = self.operteItem {
                if mVideo.isFavorite {
                    TSVideoOperator.shared.dataManager.dislikeVideo(video: mVideo) { _ in
                        self.updateLikeInfo(item: sender)
                        NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                    }
                } else {
                    TSVideoOperator.shared.dataManager.likeVideo(video: mVideo) { _ in
                        self.updateLikeInfo(item: sender)
                        NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                    }
                }
            }
        }
    }

    @objc func removeSongFromPlaylist() {
        dismiss(animated: true) {
            if let list = self.playlist, let item = self.operteItem {
                TSVideoOperator.shared.dataManager.removeVideosFromPlaylist(videos: [item], from: list) { _ in
                    THUD.toast("Removed Successfully".localized())
                    NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                }
            }
        }
    }

    @objc func addToPlayList() {
        if let mVideo = operteItem {
            let addVc: AddPlayListViewController = AddPlayListViewController(video: mVideo)
            addVc.addSuccessBlock = { [weak self] in
                NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
                self?.dismiss(animated: true, completion: {
                    THUD.toast("Added Successfully".localized())
                })
            }
            addVc.modalPresentationStyle = .overFullScreen
            present(addVc, animated: true)
        }
    }

    @objc func shareApp() {
        dismiss(animated: true) {
            let httpAppStoreLink = "https://apps.apple.com/app/id\(TSConfig.appid)"
            let text = ""
            let url = URL(string: httpAppStoreLink)!
            let image = UIImage(named: "App-Icon")!
            let vc = UIActivityViewController(activityItems: [image, text, url], applicationActivities: nil)
            vc.completionWithItemsHandler = { activity, value, _, error in
                if let type = activity, type == .copyToPasteboard {
                    UIPasteboard.general.string = httpAppStoreLink
                }
            }
        
            if UIDevice.isPad {
                if let popover = vc.popoverPresentationController {
                    popover.sourceView = self.view // 设置锚点视图
                    popover.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // 设置弹窗位置为屏幕中心
                    popover.permittedArrowDirections = [] // 禁止箭头指向
                }
            }
    
            PlayerManager.shared.rootVc?.present(vc, animated: true)
        }
    }

    /// finish.kailen
    @objc func deleteVideoAction() {
        dismiss(animated: true) {
            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 let mVideo = self.operteItem, let mVideoId = mVideo.videoId {
                    TSVideoOperator.shared.dataManager.deleteVideo(video: mVideo) { success in
                        if success {
                            /// 如果删除视频为当前播放视频,那么要清理当前播放
                            if mVideo.videoId == PlayerManager.shared.currentVideo?.videoId {
                                TSVideoOperator.shared.playerViewModel.clearCurrenVideo()
                            }
                        }
                        NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                    }
                }
                self.dismissCurrentVc()
            }))

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

    static func renamePlaylist(playlist: TSPlayList, completion: ((String) -> Void)? = nil) {
        let alertVC = UIAlertController(title: nil, message: "Playlist Name".localized(), preferredStyle: .alert)
        alertVC.addTextField { textField in
            textField.placeholder = "input name".localized()
            textField.font = UIFont.systemFont(ofSize: 16)
            textField.text = playlist.title ?? ""
        }
        let ok = UIAlertAction(title: "OK".localized(), style: .default) { _ in
            if let name = alertVC.textFields?.first?.text, !name.isEmpty {
                TSVideoOperator.shared.dataManager.editPlaylistName(playList: playlist, name: name) { _ in
                    THUD.toast("Renamed Successfully".localized())
                    NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                    completion?(name)
                }
            }
        }
        let cancel = UIAlertAction(title: "Cancel".localized(), style: .cancel)
        alertVC.addAction(cancel)
        alertVC.addAction(ok)
        PlayerManager.shared.rootVc?.present(alertVC, animated: true)
    }

    static func deletePlaylist(playlist: TSPlayList, completion: (() -> Void)? = nil) {
        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

            TSVideoOperator.shared.dataManager.deletePlaylist(playlist: playlist) { _ in
                NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                THUD.toast("Delete Successfully".localized())
                completion?()
            }

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