//
//  PlayListDetaiViewModel.swift
//  ColorfulWallpaper
//
//  Created by ni on 2024/9/19.
//

import Combine
import Foundation
import TSVideoKit

enum ListType {
    case favourite
    case recently
    case playlist
}

class PlayListDetaiViewModel: NSObject, UITableViewDataSource {
    var selectedVideos: [TSVideo] = []
    var isMuti: Bool = false
    var sortType: SortType = .downTime
    var playlist: TSPlayList?
//    var isFavourite : Bool = false
    var listType: ListType = .playlist
    @Published var selectedSingle: TSVideo?

    @Published var videos: [TSVideo] = []

    func requestData() {
        var mVideos: [TSVideo] = []

        switch listType {
        case .favourite:
            mVideos = TSVideoOperator.shared.dataManager.fetchFavouriteVideos(sort: NSSortDescriptor(key: "liketime", ascending: false))
        case .recently:
            mVideos = TSVideoOperator.shared.dataManager.fetchHistoryVideos()
        case .playlist:
            if let playlist = playlist {
                mVideos = TSVideoOperator.shared.dataManager.fetchPlaylistDetail(playlist: playlist)
            }
        }

        if sortType == .downTime {
            videos = mVideos
        } else if sortType == .upTime {
            videos = mVideos.reversed()
        } else if sortType == .downName {
            videos = mVideos.sorted {
                $0.title ?? "" < $1.title ?? ""
            }
        } else if sortType == .upName {
            videos = mVideos.sorted {
                $0.title ?? "" > $1.title ?? ""
            }
        }
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SongListCell") as! SongListCell
        if indexPath.row < videos.count {
            let video = videos[indexPath.row]
            cell.mPlaylist = playlist
            cell.bindData(video: video, isMutiSelected: isMuti, isSelected: selectedVideos.contains(where: {
                $0.videoId == video.videoId
            }),needOperate: listType != .recently)
        }
        return cell
    }
    
    /// 加入选中列表
    /// - 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)
        }
    }
}
