//
//  MusicEmptyView.swift
//  PhysicalWallPaper
//
//  Created by nkl on 2024/11/13.
//

import Combine
import Foundation
import TSVideoKit

class SongDownloadCellViewModel {
    @Published var state: DownloadButtonState = .idle(isAnimate: false)
    @Published var downloader: NewChunkDownloader?

    var dataModel: VideoOnlineModel?
    var dataVideo: TSVideo?

    private var cancellables: Set<AnyCancellable> = []

    init(dataModel: VideoOnlineModel?, video: TSVideo?) {
        self.dataModel = dataModel
        dataVideo = video
    }

    func setDownloader(_ downloader: NewChunkDownloader) {
        self.downloader = downloader
    }

    func startDownload() {
        guard let videoId = dataModel?.videoId ?? dataVideo?.videoId else { return }
        TSNewDownloadManager.shared.downloadVideo(videoId: videoId, isAudio: false) { [weak self] downloader in
            self?.downloader = downloader
            NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
        }
    }

    func resumeDownload() {
        guard let videoId = dataModel?.videoId ?? dataVideo?.videoId else { return }
        TSNewDownloadManager.shared.resumeTask(id: videoId) { [weak self] downloader in
            self?.downloader = downloader
            NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
        }
    }

    func pauseDownload() {
        guard let videoId = dataModel?.videoId ?? dataVideo?.videoId else { return }
        TSNewDownloadManager.shared.pauseTask(id: videoId) { _ in
            NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
        }
    }

    func retryDownload(isAudio: Bool = false) {
        guard let videoId = dataModel?.videoId ?? dataVideo?.videoId else { return }
        TSNewDownloadManager.shared.retryDownload(videoId: videoId, isAudio: isAudio) { [weak self] downloader in
            self?.downloader = downloader
            NotificationCenter.default.post(name: kDataChangedNotifactionName, object: nil)
        }
    }
}
