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

import Foundation
import TSVideoKit
import KLTips

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

    func requestData() {
        playLists = TSVideoOperator.shared.dataManager.fetchPlaylists()
        print("data====\(playLists.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 AddPlayListViewModel: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            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 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()
        }
  
    }
}
