//
//  DataModel.swift
//  KdanAuto
//
//  Created by 朱东勇 on 2022/11/21.
//

import Foundation

let kLoadDirectoryPathKey : String   = "kLoadDirectoryPathKey";

let kOriginPathComponent : String = "Origin Files"
let kResultPathComponent : String = "Result Files"
let kCheckPathComponent : String = "Check Files"

let kLatestReportIDKey : String = "LatestReportID"
    
class DataModel : NSObject {
    static var shared : DataModel = DataModel()
    
    var _directoryPath : String = ""
    
    /// Setter & Getter
    
    public func setDirectoryPath(_ path:String) {
        let userDefaults = UserDefaults.standard
        userDefaults.setValue(path, forKey: kLoadDirectoryPathKey)
        userDefaults.synchronize()
    }
    
    public func directoryPath() -> String {
        var path = UserDefaults.standard.value(forKey: kLoadDirectoryPathKey)
        
        if path == nil {
            path = ""
        }
        
        return path as! String
    }
    
    
    
    // Expand
    public func setIsExpand(_ fileType:String, expand:Bool) {
        let userDefaults = UserDefaults.standard
        if expand {
            userDefaults.setValue("true", forKey: String("\(fileType)-expand"))
        }else {
            userDefaults.setValue(nil, forKey: String("\(fileType)-expand"))
        }
        userDefaults.synchronize()
    }
    
    public func isExpand(_ fileType:String) -> Bool {
        let userDefaults = UserDefaults.standard
        
        return userDefaults.value(forKey: String("\(fileType)-expand")) != nil
    }
    
    
    public func originFilesFor(_ fileType:String, type:String) -> [String] {
        var path = self.directoryPath() as NSString
        path = path.appendingPathComponent(fileType) as NSString
        path = path.appendingPathComponent(type) as NSString
        path = path.appendingPathComponent(kOriginPathComponent) as NSString
        
        if !FileManager.default.fileExists(atPath: path as String) {
            return []
        }
        
        let items =  try? FileManager.default.contentsOfDirectory(atPath: path as String)
        let subPaths = NSMutableArray(array: items ?? [])
        subPaths.remove(".DS_Store")
        
        return subPaths as! [String]
    }
    
    public func generaNewReportID() -> String {
        let string = NSString.init(format: "%.0f", NSDate.now.timeIntervalSince1970) as String
        
        let userDefaults = UserDefaults.standard
        userDefaults.set(string, forKey: kLatestReportIDKey)
        userDefaults.synchronize()
        
        return string
    }
    
    public func latestReportID() -> String? {
        let userDefaults = UserDefaults.standard
        
        return userDefaults.value(forKey: kLatestReportIDKey) as? String
    }
    
    /// Save Data
    
}
