//
//  MPPositive_SongViewModel.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/8.
//

import UIKit
import AVKit
import AVFoundation

class MPPositive_SongViewModel: NSObject {
    ///排序号
    var index:Int!
    ///播放实例
    @objc dynamic var resourcePlayerItem:MP_AVPlayerItem!
    ///播放媒体
    var resourcePlayerAsset:MP_AVURLAsset!
    ///播放路径
    var resourcePlayerURL:URL!
    ///封面
    var coverUrl:URL?
    ///标题
    var title:String?
    ///副标题
    var subtitle:String?
    ///歌词
    var lyrics:String?
    ///相关内容ID
    var relatedId:String?
    ///是否收藏
    var isCollection:Bool?
    ///是否下载
    var isDlownd:Bool?
    ///是否被KVO监听
    var isKVO:Bool = false
    ///是否完成了预加载
    var isPreload:Bool = false
    ///音乐实体
    var song:MPPositive_SongItemModel!
    init(_ song:MPPositive_SongItemModel) {
        super.init()
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(switchURL403Action(_ :)), notificationName: .player_asset_403)
        self.song = song
        configure()
    }
    deinit {
        print("\(title ?? "")被销毁了")
        NotificationCenter.default.removeObserver(self)
        MP_NetWorkManager.shared.removeVideoResource(song.videoId)
        //销毁实例
        resourcePlayerItem = nil
        resourcePlayerAsset = nil
        resourcePlayerURL = nil
        isKVO = false
    }
    //数据配置
    func configure() {
        reloadCollectionAndDownLoad{
            [weak self] in
            guard let self = self else {return}
            index = song.index
            //标题
            if song.title != nil {
                title = song.title!
            }
            //副标题(作者/专辑)
            if song.shortBylineText != nil {
                subtitle = song.shortBylineText!
            }
            //封面路径默认取最后一条
            if song.reviewUrls?.first != nil {
                coverUrl = .init(string: song.reviewUrls!.last!)
            }
            //创建队列组
            let group = DispatchGroup()
            //执行数据补全
            group.enter()
            //补全歌词id和相关内容id
            if song.lyricsID == nil || song.relatedID == nil {
                //需要网络请求补全数据
                improveDataforLycirsAndRelated(song) {[weak self] (result) in
                    guard let self = self else {return}
                    if let resultID = result.0 {
                        song.lyricsID = resultID
                    }
                    if let relatedID = result.1 {
                        song.relatedID = relatedID
                    }
                    group.leave()
                }
            }else {
                //歌词id和相关内容id是完整的
                group.leave()
            }
            group.enter()
            //补全资源路径和封面路径
            //判断当前videoID是否进行过下载
            if let resource = MP_DownloadManager.shared.getDocumentsFileURL(song.videoId) {
                //下载过，将资源添加
                song.resourceUrls = [resource]
                group.leave()
            }else {
                //没有下载过
                //调用网络请求补全数据
                improveDataforResouceAndCover(song) { [weak self] resourceUrls, coverUrls in
                    guard let self = self else {return}
                    if let resourceUrls = resourceUrls {
                        song.resourceUrls = resourceUrls.0
                        song.itags = resourceUrls.1
                        song.mimeTypes = resourceUrls.2
                    }
                    song.coverUrls = coverUrls
                    group.leave()
                }
            }
            //当所有内容都修改完毕后
            group.notify(queue: .main) {
                [weak self] in
                guard let self = self else {return}
                //更新播放资源
                if let first = song.resourceUrls?.first {
                    resourcePlayerURL = .init(string:first)
                    if isDlownd == true {
                        //下载了
                        resourcePlayerAsset = .init(LocalURL: resourcePlayerURL!, videoId: song.videoId, title: title ?? "")
                    }else {
                        //未下载
                        resourcePlayerAsset = .init(resourcePlayerURL!, videoId: song.videoId, title: title ?? "")
                    }
                    resourcePlayerItem = .init(asset: resourcePlayerAsset)
                    
                }
                //更新歌词
                if song.lyrics != nil {
                    lyrics = song.lyrics
                }else {
                    if song.lyricsID != nil {
                        //执行网络请求拿到歌词数据
                        MP_NetWorkManager.shared.requestLyric(song.lyricsID!) {[weak self] lyrics in
                            self?.lyrics = lyrics
                            self?.song.lyrics = lyrics
                        }
                    }
                }
                //更新相关内容
                if song.relatedID != nil {
                    relatedId = song.relatedID
                }
            }
        }
        
    }
    //页面状态更新
    func reloadCollectionAndDownLoad(_ completion:(() -> Void)? = nil) {
        //检索是否收藏
        MPPositive_CollectionSongModel.fetch(predicate: .init(format: "videoId == %@", song.videoId)) { [weak self] results in
            guard let self = self else {return}
            isCollection = results.count != 0
        }
        //检索是否下载
        MP_DownloadManager.shared.isDownloadedFileDocuments(song.videoId, completion: {[weak self] statu in
            guard let self = self else {return}
            isDlownd = statu
            completion?()
        })
    }
    //监听到403错误，重新匹配资源路径
    @objc private func switchURL403Action(_ notification:Notification) {
        guard let path = notification.object as? String, song != nil else {return}
        song.resourceUrls?[0] = path
        resourcePlayerURL = .init(string: path)
    }
}
