//
//  MusicEmptyView.swift
//  PhysicalWallPaper
//
//  Created by nkl on 2024/11/13.
//

import CoreData
import Foundation
import TSVideoKit
import UIKit
import KLTips

class SongListViewModel: NSObject {
    @Published var videos: [TSVideo] = []
    var isMutiSelectModel: Bool = false
    var selectedVideos: [TSVideo] = []
    var sortType: SortType = .downTime

    var playLists: [TSPlayList] = []
    var recentlyVideos  : [TSVideo] = []

    var isEmptyData: Bool {
        videos.isEmpty && unFinishedVideo.isEmpty
    }

    var favouriteVideos: [TSVideo] {
        videos.filter {
            $0.isFavorite
        }
    }
    
    

    var sortDescriptor: NSSortDescriptor {
        let sortDescriptor: NSSortDescriptor

        switch sortType {
        case .upTime:
            sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: true)
        case .downTime:
            sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: false)
        case .upName:
            sortDescriptor = NSSortDescriptor(key: "title", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
        case .downName:
            sortDescriptor = NSSortDescriptor(key: "title", ascending: false, selector: #selector(NSString.localizedStandardCompare(_:)))
        }
        return sortDescriptor
    }

    var unFinishedVideo: [SongDownloadCellViewModel] = []

    func requestData() {
        videos = TSVideoOperator.shared.dataManager.fetchCachedVideos(sort: sortDescriptor)
        playLists = TSVideoOperator.shared.dataManager.fetchPlaylists()
        recentlyVideos = TSVideoOperator.shared.dataManager.fetchHistoryVideos()
        let videos = TSVideoOperator.shared.dataManager.fetchNotCachedVideos()
        unFinishedVideo = videos.map {
            SongDownloadCellViewModel(dataModel: nil, video: $0)
        }
    }
}

extension SongListViewModel: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            if isMutiSelectModel {
                return 0
            } else {
                return unFinishedVideo.count
            }

        } else {
            return videos.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SongDownloadCell") as! SongDownloadCell
            return cell
        } else {
            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: isMutiSelectModel, isSelected: isSelected,needOperate: true)
                }
                return cell
            }
            return SongListCell()
        }
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row < unFinishedVideo.count {
                let viewModel = unFinishedVideo[indexPath.row]
                if let video = viewModel.dataVideo, let videoId = video.videoId {
                    TSVideoOperator.shared.downloadManager.cancelTask(id: videoId) {
                        self.requestData()
                    }
                }
            }
        } else {
            if indexPath.row < videos.count {
                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

                    let video = self.videos[indexPath.row]
                    /// 如果删除视频为当前播放视频，那么minibar 要初始化
                    if video.videoId == PlayerManager.shared.currentVideo?.videoId {
                        TSVideoOperator.shared.playerViewModel.clearCurrenVideo()
                    }
                    /// 歌单也要删除
                    PlayerManager.shared.player?.playControl.viewModel.currentVideos.removeAll {
                        $0.videoId == video.videoId
                    }

                    TSVideoOperator.shared.dataManager.deleteVideo(video: video) { _ in
                        self.requestData()
                    }

                }))
                PlayerManager.shared.rootVc?.present(ac, 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)
        }
    }

    ///todo.kailen
//    func showOperationViewController(video: TSVideo) {
//        let operationVc = RingOperateViewController(operateTypes: [.edit, .addPlaylist, .like, .delete, .share, .ring])
//        operationVc.video = video
//        operationVc.presentVc = PlayRootController.shared
//        operationVc.modalPresentationStyle = .overFullScreen
//        PlayRootController.shared.present(operationVc, animated: true)
//    }
    
}
