//
//  SearchResultViewModel.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/11.
//

import Alamofire
import CoreData
import Foundation
import KLExtension
import SwiftUI
import TSVideoKit

enum SearchType: String {
    case video = "v"
    case channel = "c"
    case playlist = "p"
}

struct SearchModel {
    var query: String
    var type: SearchType = .video
    var next: String = ""
}

enum CWLoadState {
    case idle
    case loading
    case reloading
    case fail
    case loadingMore
    case success
    case empty
}

class SearchResultViewModel: NSObject {
    var keyword: String = ""

    /// 加载状态
    @Published var loadState: CWLoadState = .idle

    /// 数据源组
//    @Published var datas: [VideoListDetailData] = []
    @Published var datas: [SongDownloadCellViewModel] = []

    /// 是否需要刷新页面
    @Published var needReload: Bool = false

    /// 搜索模型
    var searchModel: SearchModel = .init(query: "")

    var hasNextPage: Bool {
        let hasNext = !searchModel.next.isEmpty
        return hasNext
    }
    
    override init() {
        super.init()
        
        NotificationCenter.default.addObserver(self, selector: #selector(retryAudio(notify:)), name: kSingleVideoFailNotifactionName, object: nil)
    }
    
    @objc func retryAudio(notify:Notification) {
        if let videoId = notify.object as? String {
            if let viewModel = datas.first(where: {
                $0.downloader?.groupId == videoId
            }) {
                viewModel.retryDownload(isAudio: true)
            }
        }
    }

    /// 初始加载
    func requestData() {
        loadState = .loading
        loadData()
    }

    /// 下啦刷新
    func reloadData() {
        loadState = .reloading
        searchModel.next = ""
        loadData()
    }

    /// 上啦加载
    func loadMoreData() {
        loadState = .loadingMore
        loadData()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension SearchResultViewModel {
    func loadData() {
        TSApiManager.shared.ts_searchVideo(keyword: searchModel.query, requestId: prase_search_key, next: searchModel.next) { result, next in
            switch result {
            case let .success(modes):
                /// 下拉刷新覆盖 ｜｜ 初次加载
                if self.loadState == .reloading ||
                    self.loadState == .loading {
                    self.datas = modes.map({
                        SongDownloadCellViewModel(dataModel: $0, video: nil)
                    })
                } else {
                    /// 其他新增
                    self.datas.append(contentsOf: modes.map({
                        SongDownloadCellViewModel(dataModel: $0, video: nil)
                    }))
                }
                self.searchModel.next = next
                if self.datas.isEmpty {
                    self.loadState = .empty
                } else {
                    self.loadState = .success
                }

            case let .failure(error):
                if self.datas.isEmpty {
                    self.loadState = .fail
                }
                print("error")
            }
        }
    }
}

extension SearchResultViewModel: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        datas.count
    }

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

    func showOperationViewController(videoId: String) {
        if let video = TSVideoOperator.shared.dataManager.fetchVideo(videoId: videoId) {
            let vc = CWOperateViewController()
            vc.modalPresentationStyle = .overFullScreen
            vc.operteItem = video
            PlayerManager.shared.rootVc?.present(vc, animated: true)
        }
     
    }
}
