//
//  GeneratorChecker.swift
//  
//
//  Created by Thibaut Schmitt on 22/12/2021.
//

import Foundation

public class GeneratorChecker {
    
    /// Return `true` if  inputFile is newer than extensionFile, otherwise `false`
    public static func shouldGenerate(force: Bool, inputFilePath: String, extensionFilePath: String) -> Bool {
        guard force == false else {
            return true
        }
        
        return Self.isFile(inputFilePath, moreRecenThan: extensionFilePath)
    }
    
    public static func isFile(_ fileOne: String, moreRecenThan fileTwo: String) -> Bool {
        let fileOneURL = URL(fileURLWithPath: fileOne)
        let fileTwoURL = URL(fileURLWithPath: fileTwo)
        
        let fileOneRessourceValues = try? fileOneURL.resourceValues(forKeys: [URLResourceKey.contentModificationDateKey])
        let fileTwoRessourceValues = try? fileTwoURL.resourceValues(forKeys: [URLResourceKey.contentModificationDateKey])
        
        guard let fileOneModificationDate = fileOneRessourceValues?.contentModificationDate,
              let fileTwoModificationDate = fileTwoRessourceValues?.contentModificationDate else {
            print("⚠️ Could not compare file modication date. ⚠️ (assume than file is newer)")
            // Date not available -> assume than fileOne is newer than fileTwo
            return true
        }
        
        if fileOneModificationDate >= fileTwoModificationDate {
            debugPrint("File one is more recent than file two.")
            return true
        }
        
        return false
    }
    
}
