//
//  FilterBarViewModel.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/10.
//

import Foundation
import TSVideoKit

enum MineRingTopType {
    case `default`
    case mutiselect
}

class FilterBarViewModel {
    @Published var videos: [TSVideo] = []
    @Published var barType: MineRingTopType = .default
    @Published var selectedVideos: [TSVideo] = []
    @Published var sortType: SortType = .downTime
    var playlist: TSPlayList?
    var isFromPlaylist: Bool = false

    init(videos: [TSVideo], barTyle: MineRingTopType, selectedVideos: [TSVideo], sortType: SortType) {
        self.videos = videos
        barType = barTyle
        self.selectedVideos = selectedVideos
        self.sortType = sortType
    }

    var selectTitle: String {
        return "Select All".localized() + " (\(selectedVideos.count)/\(videos.count)) "
    }

    var playTitle: String {
        return "Play All".localized() + " (\(videos.count)) "
    }

    func showSortOperateView(parent: UIViewController) {
        let vc = SortMenuViewController(type: sortType)
        vc.modalPresentationStyle = .overFullScreen
        vc.didSelectedSortType = { type in
            self.sortType = type
        }
        parent.present(vc, animated: true)
    }

    /// 播放全部按钮
    func playAllVideos() {
        if let firstVideo = videos.first {
            PlayerManager.shared.player?.playControl.viewModel.loopMode = .cyclic
            PlayerManager.shared.playVideo(video: firstVideo, list: videos, scene: .local, onceAdKey: "")
        }
    }

    /// 多选按钮点击
    func beginMutiSelect() {
        barType = .mutiselect
        PlayerManager.shared.showMutiOperateView(isFromPlaylist: isFromPlaylist, playlist: playlist)
    }

    /// 多选取消
    func doneMutiSelect() {
        barType = .default
        PlayerManager.shared.hideMutiOperateView()
    }

    /// 加入选中列表
    /// - 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)
        }
    }
}
