//
//  LNVisitedTimeWrapper.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/8.
//

import Foundation
import AutoCodable


@propertyWrapper
struct LNVisitedTimeWrapper<T: Codable>: Codable {
    private var obj: T
    private(set) var visited: TimeInterval = curTime
    
    var wrappedValue: T {
        mutating get {
            visited = curTime
            return obj
        }
        set {
            obj = newValue
        }
    }
    
    var projectedValue: LNVisitedTimeWrapper { self }
    
    init(wrappedValue: T) {
        self.obj = wrappedValue
        visited = curTime
    }
    
    private init(obj: T, visited: TimeInterval) {
        self.obj = obj
        self.visited = visited
    }
    
    private enum CodingKeys: String, CodingKey {
        case obj
        case visited
    }
    
    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        let obj = try container.decode(T.self, forKey: .obj)
        let visited = try container.decode(TimeInterval.self, forKey: .visited)
        
        self.init(obj: obj, visited: visited)
    }
    
    func encode(to encoder: any Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(obj, forKey: .obj)
        try container.encode(visited, forKey: .visited)
    }
}
