//
//  LoadDataMusic.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/1.
//

import UIKit
///音乐数据集合控制器
class LoadDataMusic: NSObject {
    static let shared = LoadDataMusic()
    ///全部音乐资源
    var alllistMusics:[MusicViewModel] = []
    ///用户上传资源
    var userlistMusics:[MusicViewModel] = []
    ///本地全部资源
    var locallistMusics:[MusicViewModel] = []
    ///首页展示-第0层（本地三条加一条用户最后播放数据）
    var homeZeroMusics:[MusicViewModel] = []
    ///首页展示-第1层（本地数据，ablum为1）
    var homeFirstMusics:[MusicViewModel] = []
    ///首页展示-第2层（本地数据，ablum为2）
    var homeSecondMusics:[MusicViewModel] = []
    ///首页展示-第3层（本地数据，ablum为3）
    var homeThirdMusics:[[MusicViewModel]] = []
    private override init() {
        super.init()
        if (UserDefaults.standard.bool(forKey: "FirstBulid")) == false {
            //配置本地数据
            plistDatatoModel()
            UserDefaults.standard.set(true, forKey: "FirstBulid")
            print("Create data successfully")
        }
    }
    
    /// 数据配置
    /// - Parameter complete: 当模型组配置完成后执行该事件
    public func reloadListData() {
        //清空各项数组内容
        alllistMusics = []
        userlistMusics = []
        locallistMusics = []
        homeZeroMusics = []
        homeFirstMusics = []
        homeSecondMusics = []
        homeThirdMusics = []
        //重新装填数据
        let all = MusicModel.fetchAll()
        all.forEach { item in
            //筛选本地与用户上传数据
            if item.isLocal == true {
                locallistMusics.append(.init(item))

            }else {
                userlistMusics.append(.init(item))
            }
            //全部数据
            alllistMusics.append(.init(item))
        }
        //分类展示数据
        homeFirstMusics = locallistMusics.filter{($0.type == .First)}
        homeSecondMusics = locallistMusics.filter{($0.type == .Second)}
        homeThirdMusics = convertToTwoArray(locallistMusics.filter{($0.type == .Third)}, raw: 3)
        //取出固定内容
        homeZeroMusics.append(homeThirdMusics.last!.last!)
        homeZeroMusics.append(homeSecondMusics.last!)
        homeZeroMusics.append(homeFirstMusics.last!)
        if userlistMusics.count != 0 {
            homeZeroMusics.append(userlistMusics.last!)
        }
    }
    //获取本地资源Plist，并转化为音乐模型数组
    private func plistDatatoModel() {
        let plistPath = Bundle.main.path(forResource: "Resource", ofType: "plist")!
        let dictArray = NSArray(contentsOfFile: plistPath)
        dictArray?.forEach({ (item) in
            let dict = item as! [String : AnyObject]
            let music = MusicModel.create()
            music.identifier = dict["identifier"] as? String
            music.title = dict["title"] as? String
            music.duration = dict["duration"] as! Double
            music.cover = UIImage(named: dict["cover"] as! String)!.pngData()!
            music.author = dict["author"] as? String
            music.album = dict["album"] as! Int16
            music.isLocal = dict["isLocal"] as! Bool
            music.path = dict["path"] as! String
            music.creationTime = Date().timeZone()
        })
        MusicModel.save()
    }
    
    /// 将一维音乐数组转为二维音乐数组
    /// - Parameters:
    ///   - array: 原音乐数组
    ///   - raw: 分割个数
    /// - Returns: 返回的二维数组
    private func convertToTwoArray(_ array:[MusicViewModel], raw:Int) -> [[MusicViewModel]] {
        let twoDArray = stride(from: 0, to: array.count, by: raw).map { (index) -> [MusicViewModel] in
            if (index + raw) > array.count {
                return Array(array[index...])
            } else {
                return Array(array[index..<index + raw])
            }
        }
        return twoDArray
    }
}
