//
//  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!
    ///音乐资源路径
    var resourcePlayerItem:AVPlayerItem!
    ///封面
    var coverUrl:URL?
    ///标题
    var title:String?
    ///副标题
    var subtitle:String?
    ///歌词
    var lyrics:String?
    ///相关内容ID
    var relatedId:String?
    ///是否完成预加载
    var isPreloading:Bool?
    ///是否收藏
    var isCollection:Bool?
    ///是否下载
    var isDlownd:Bool?
    ///音乐实体
    var song:MPPositive_SongItemModel!
    ///观察是否执行KVO
    var isKvo:Bool = false
    init(_ song:MPPositive_SongItemModel) {
        super.init()
        self.song = song
        configure()
    }
    deinit {
        if isKvo == true {
            resourcePlayerItem.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp")
            isKvo = false
        }
    }
    //数据配置
    private func configure() {
        index = song.index
        //资源路径默认取第一条
        if song.resourceUrls?.first != nil {
            let first = URL(string: song.resourceUrls!.first!)
            resourcePlayerItem = .init(url: first!)
        }
        //封面路径默认取最后一条
        if song.coverUrls?.first != nil {
            coverUrl = .init(string: song.coverUrls!.last!)
        }
        //标题
        if song.title != nil {
            title = song.title!
        }
        //副标题(作者/专辑)
        if song.shortBylineText != nil {
            subtitle = song.shortBylineText!
        }
        //歌词
        if song.lyricsID != nil {
            //执行网络请求拿到歌词数据
            MP_NetWorkManager.shared.requestLyric(song.lyricsID!) {[weak self] lyrics in
                self?.lyrics = lyrics
            }
        }
        //相关内容
        if song.relatedID != nil {
            relatedId = song.relatedID
        }
        //检索是否收藏
        
        //检索是否下载
        
    }
    //MARK: - 资源预加载
    //检测资源是否能被预加载
    private func canBePreloaded() -> Bool {
        return self.isPreloading ?? false
    }
    ///异步预加载
    func preloadPlayerItem() {
        //执行预加载
        guard canBePreloaded() == false else {
            print("\(title ?? "")已经预加载了")
            return
        }
        print(resourcePlayerItem.status)
        //手动触发，以此加载数据
        self.resourcePlayerItem.seek(to: .zero) {[weak self] _ in
            guard let self = self else {return}
            //实行异步监听预加载
            DispatchQueue.global(qos: .background).async {
                if self.isKvo == false {
                    //为playerItem添加监听
                    self.resourcePlayerItem.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
                    self.isKvo = true
                }
            }
        }
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "playbackLikelyToKeepUp" {
            if let playbackLikelyToKeepUp = change?[.newKey] as? Bool, playbackLikelyToKeepUp == true {
                //当前资源已经预加载到合适的程度，移除KVO监听
                print("\(title ?? "")预加载到合适的进度")
                if isKvo == true {
                    resourcePlayerItem.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp")
                    isKvo = false
                }
                //表示已经完成了预加载
                isPreloading = true
            }
        }
    }
}
