//
//  WP_4KModel.swift
//  wallpaper_project


import UIKit
@objcMembers

class WP_4KModel: NSObject,Decodable,Encodable {
    
    var title:String?
    var thumbnail:String?
    var preview:String?
    var is_free:Int?
    var category:Int?
    var id:Int?
    var cnt_like:Int?

    enum CodingKeys: String, CodingKey {
           case title
           case thumbnail
           case preview
           case is_free
           case category
           case id
           case cnt_like
       }
       
       // 实现 Decodable 协议中的初始化方法
       required override init() {
           super.init()
       }
       
       // 实现 Encodable 协议中的编码方法
       func encode(to encoder: Encoder) throws {
           var container = encoder.container(keyedBy: CodingKeys.self)
           try container.encode(title, forKey: .title)
           try container.encode(thumbnail, forKey: .thumbnail)
           try container.encode(preview, forKey: .preview)
           try container.encode(is_free, forKey: .is_free)
           try container.encode(category, forKey: .category)
           try container.encode(id, forKey: .id)
           try container.encode(cnt_like, forKey: .cnt_like)
       }
    
}

class WP_PhotoAlbum: NSObject,Codable {
    var img:String?
    
    init(img: String?) {
            self.img = img
        }
}
// 偏好设置管理器
class PreferencesManager {
    static let shared = PreferencesManager()
    let defaults = UserDefaults.standard
    
    // 保存模型对象数组
    func saveRakModels(_ models: [WP_PhotoAlbum]) {
        do {
            let encoder = JSONEncoder()
            let encodedData = try encoder.encode(models)
            defaults.set(encodedData, forKey: "rakModels")
        } catch {
            print("Error encoding rakModels: \(error)")
        }
    }
    
    // 添加新的模型对象
    func addRakModel(_ model: WP_PhotoAlbum) {
        var existingModels = retrieveRakModels() ?? [] // 检索之前保存的数据，如果没有数据则使用空数组
        existingModels.append(model) // 将新的数据模型添加到数组中
        saveRakModels(existingModels) // 保存数组到偏好设置中
    }
    
    // 检索模型对象数组
    func retrieveRakModels() -> [WP_PhotoAlbum]? {
        if let savedData = defaults.data(forKey: "rakModels") {
            do {
                let decoder = JSONDecoder()
                let loadedModels = try decoder.decode([WP_PhotoAlbum].self, from: savedData)
                return loadedModels
            } catch {
                print("Error decoding rakModels: \(error)")
                return nil
            }
        }
        return nil
    }
}
