//
//  PlayListViewModel.swift
//  ColorfulWallpaper
//
//  Created by ni on 2024/9/18.
//

import CoreData
import Foundation
import KLTips
import TSVideoKit
import UIKit

class PlayListViewModel: NSObject {
    @Published var playLists: [TSPlayList] = []
    var needMore: Bool = true

    var recentlyCount: Int = 0
    var likeCount: Int = 0

    func requestData() {
        playLists = TSVideoOperator.shared.dataManager.fetchPlaylists()
        recentlyCount = TSVideoOperator.shared.dataManager.fetchHistoryVideos().count
        likeCount = TSVideoOperator.shared.dataManager.fetchFavouriteVideos(sort: NSSortDescriptor(key: "createdAt", ascending: true)).count
    }

    func reloadData() {
        requestData()
    }

    func creatPlayList(name: String, complete: (UUID?) -> Void) {
        TSVideoOperator.shared.dataManager.createPlaylist(name: name) { playlistId in

            if let id = playlistId {
                reloadData()
                THUD.toast("Created Successfully".localized())
                NotificationCenter.default.post(name: .K_RefreshNotifaction, object: nil)
                complete(id)
            } else {
                complete(nil)
            }
        }
    }
}

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayListCell") as? PlayListAddCell {
                return cell
            }
            return PlayListAddCell()
        } else if indexPath.section == 1 {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayListFavouriteCell") as? PlayListFavouriteCell {
                cell.updateCount(count: likeCount)
                return cell
            }
            return PlayListFavouriteCell()
        } else {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayListCell") as? PlayListCell {
                if indexPath.row < playLists.count {
                    let playList = playLists[indexPath.row]
                    cell.bindData(list: playList, needMoreButton: needMore)
                }
                return cell
            }
            return PlayListCell()
        }
    }
}
