//
// © 2017-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import UIKit
import CocoaLumberjack

class PersistenceController {
    static func store<T: Codable>(_ item: T) {
		let name = String(describing: T.self)
        do {
            let data = try JSONEncoder().encode(item)
            let p = pathURL(forName: name)
            guard let pathURL = p else {
                DDLogError("Could not get path for: \(name)")
                return
            }
            
            let fileManager = FileManager.default
            if fileManager.fileExists(atPath: pathURL.path) {
                try fileManager.removeItem(at: pathURL)
            }
            
            try data.write(to: pathURL)
        }
        catch let error {
            DDLogError("Could not store: \(name) error: \(error)")
            return
        }
    }
    
    static func load<T: Codable>() -> T? {
        let name = String(describing: T.self)
        let d = fetch(forName: name)
        
        guard let data = d else {
            return nil
        }
        
        do {
            let object = try JSONDecoder().decode(T.self, from: data)
            return object
        }
        catch {
            DDLogError("Could not decode: \(name) error: \(error)")
            return nil
        }
    }
    
    private static func pathURL(forName name: String) -> URL? {
        let fileManager = FileManager.default
        let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
        
        guard let documentDirectory = urls.first else {
            return nil
        }
            // This is where the database should be in the documents directory
        let path = documentDirectory.appendingPathComponent(name)
        return path
    }
    
    private static func fetch(forName name: String) -> Data? {
        let p = pathURL(forName: name)
        guard let pathURL = p  else {
            return nil
        }
        
        do {
            let data = try Data(contentsOf: pathURL)
            return data
        }
        catch {
            return nil
        }
    }
}
