//
//  SongListManageViewModel.swift
//  TSLiveWallpaper
//
//  Created by nkl on 2024/12/24.
//

import Foundation
import TSVideoKit

class SongListManageViewModel: NSObject, UITableViewDataSource {
    var videos: [TSVideo] = []
    var playlist: TSPlayList?
    @Published var selectedVideos: [TSVideo] = []

    var isSelectedAll: Bool {
        selectedVideos.count == videos.count
    }

    var selectedTitle: String {
        "Select (\(selectedVideos.count)/\(videos.count))"
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return videos.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "SongListCell") as? SongListCell {
            if indexPath.row < videos.count {
                let videoModel = videos[indexPath.row]
                let isSelected = selectedVideos.contains(where: {
                    $0.videoId == videoModel.videoId
                })
                cell.bindData(video: videoModel, isMutiSelected: true, isSelected: isSelected, needOperate: false)
            }
            return cell
        }
        return SongListCell()
    }

    func deleteSelectedVideos(parent: UIViewController, complete: @escaping () -> Void) {
        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
            }
            let needRestart = videoIds.contains { id in
                id == TSVideoOperator.shared.playerViewModel.currentVideo?.videoId
            }
            TSVideoOperator.shared.dataManager.deleteVideos(videos: self.selectedVideos) { _ in

                PlayerManager.shared.hideMutiOperateView()

                for item in videoIds {
                    TSVideoOperator.shared.playerViewModel.currentVideos.removeAll { $0.isFault }
                    self.videos.removeAll {
                        $0.videoId == item
                    }
                }

                // 播放删完列表后的第一首
                let newVideos = TSVideoOperator.shared.playerViewModel.currentVideos
                if let video = newVideos.first {
                    if needRestart {
                        /// 播放的时候回刷新列表不用重复刷
                        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)
                }
                complete()
            }

        }))

        parent.present(ac, animated: true)
    }

    func selectAllVideos() {
        selectedVideos = videos
    }

    func deSelectAllVideos() {
        selectedVideos.removeAll()
    }

    func removeSelectedFromPlaylist(playlist: TSPlayList, complete: @escaping () -> Void) {
        if selectedVideos.isEmpty {
            return
        }
        TSVideoOperator.shared.dataManager.removeVideosFromPlaylist(videos: selectedVideos, from: playlist) { _ in
            complete()
        }
    }

    func addSelectedToPlaylist(parent: UIViewController, complete: @escaping () -> Void) {
        if selectedVideos.isEmpty {
            return
        }
        let vc = AddPlayListViewController(videos: selectedVideos)
        vc.addSuccessBlock = {
            complete()
        }
        parent.present(vc, animated: true)
    }

    /// 加入选中列表
    /// - Parameter video: video
    func addToSelectedList(video: TSVideo) {
        // 已经有了，那么删除
        if selectedVideos.contains(where: {
            $0.videoId == video.videoId
        }) {
            selectedVideos.removeAll(where: {
                $0.videoId == video.videoId
            })
        } else {
            selectedVideos.append(video)
        }
    }
}
