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

import Foundation
import TSVideoKit
import UIKit

class PlayDetailListViewModel: NSObject, UITableViewDataSource {
    var playScene: TSPlayScene = .local
    var videos: [TSVideo] = []
    var recommendDatas: [VideoOnlineModel] = []
    var needRecommend: Bool {
        return playScene == .recommend || playScene == .online
    }

    var indexOfCurrentVideo: IndexPath? {
        if needRecommend {
            if let index = recommendDatas.firstIndex(where: { video in
                video.videoId == PlayerManager.shared.currentVideo?.videoId
            }) {
                return IndexPath(row: index, section: 0)
            }
            return nil
        } else {
            if let index = videos.firstIndex(where: { video in
                video.videoId == PlayerManager.shared.currentVideo?.videoId
            }) {
                return IndexPath(row: index, section: 0)
            }
            return nil
        }
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "PlayDetailListViewCell") as? PlayDetailListViewCell else {
            return SongListCell()
        }

        let dataCount = needRecommend ? recommendDatas.count : videos.count

        if indexPath.row < dataCount {
            if needRecommend {
                cell.bindData(data: recommendDatas[indexPath.row])
            } else {
                cell.bindData(video: videos[indexPath.row])
            }

            cell.deleteButtonClickEvent = { videoId in

                if TSVideoOperator.shared.playerViewModel.currentVideo?.videoId == videoId {
                    TSVideoOperator.shared.playerController.playNext()
                }
                // 删除视频数据
                if TSVideoOperator.shared.playerViewModel.scene == .online || TSVideoOperator.shared.playerViewModel.scene == .recommend  {
                    TSVideoOperator.shared.playerViewModel.recommendDatas.removeAll { model in
                        model.videoId == videoId
                    }
                    self.recommendDatas.removeAll { $0.videoId == videoId }
                } else {
                    TSVideoOperator.shared.playerViewModel.currentVideos.removeAll { $0.videoId == videoId }
                    self.videos.removeAll { $0.videoId == videoId }
                }
                tableView.reloadData()
            }
        }

        return cell
    }
}
