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

import Foundation
import TSVideoKit

class LocalSearchViewModel: NSObject {
    @Published var videos: [TSVideo] = []

    var keyword: String = "" {
        didSet {
            requestAssociateRelate()
        }
    }

    var task: URLSessionTask?
    
    var sort : NSSortDescriptor?

    func requestAssociateRelate() {
        if keyword.isEmpty {
            return
        }
        
        self.videos = TSVideoOperator.shared.dataManager.fuzzySearchVideos(byTitle: keyword,sort: sort)
    }
}

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "SongListCell", for: indexPath) as? SongListCell {
            if indexPath.row < videos.count {
                let video = videos[indexPath.row]
                cell.bindData(video: video)
            }
               
            return cell
        }
        return SongListCell()
    }
}
