//
//  MPPositive_GridLoadViewModel.swift
//  relax.offline.mp3.music
//
//  Created by Mr.Zhou on 2024/7/12.
//

import UIKit

class MPPositive_GridLoadViewModel: NSObject {
    static let shared = MPPositive_GridLoadViewModel()
    var grideViewModels:[MPPositive_GridViewModel] = []
    
    private override init() {
        super.init()
        if let data = chachedData() {
            grideViewModels = data
        }
    }
    //更新grideModel
    func reloadGrides() {
        MP_NetWorkManager.shared.requestGenres { [weak self] array in
            guard let self = self else {return}
            DispatchQueue.main.async {
                self.grideViewModels = array
                self.cacheResponseData(self.grideViewModels)
                //发布通知
                NotificationCenter.notificationKey.post(notificationName: .search_gride_reload)
            }
        }
    }
    //存入默认数据
    private func cacheResponseData(_ array: [MPPositive_GridViewModel]) {
        guard grideViewModels.count != 0 else {
            print("Search Gride数据未加载，无法缓存")
            return
        }
        //将数据转为jsonData
        do{
            let jsonData = try JSONEncoder().encode(array)
            //使用UserDefaults存入缓存数据
            UserDefaults.standard.set(jsonData, forKey: "SearchGride")
            print("已经将Search Gride数据缓存")
        }catch{
            //转为jsonData失败
            print("Search Gride数据转为Data失败，失败原因\(error)")
        }
    }
    //获取默认数据
    private func chachedData() -> [MPPositive_GridViewModel]? {
        guard let cacheData = UserDefaults.standard.data(forKey: "SearchGride") else {
            print("获取Search Gride缓存数据失败")
            return nil
        }
        do {
            let array:[MPPositive_GridViewModel] = try JSONDecoder().decode([MPPositive_GridViewModel].self, from: cacheData)
            print("已经将Search Gride缓存数据取出")
            return array
        } catch {
            //转为jsonData失败
            print("获取Search Gride缓存数据失败，失败原因\(error)")
            return nil
        }
    }
}
