//
//  URL+Extensions.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 01/03/2024.
//

import Foundation

extension URL {
    
    static var savedDateFormatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "DD/MM/yyyy"
        return df
    }()

    static var importDateFormatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "MM-yyyy"
        return df
    }()
    
    var dateFromPath: Date {
        let found = deletingPathExtension().path().components(separatedBy: "-").suffix(2).joined(separator: "-")
        if let date = URL.importDateFormatter.date(from: found) {
            return date
        } else {
            return Date()
        }
    }
    
    var index: Int {
        if let i = path().dropLast(12).last?.wholeNumberValue {
            return i
        }
        return 0
    }
    
    var manData: Bool {
        path().contains("MESSIEURS")
    }

    var womanData: Bool {
        path().contains("DAMES")
    }

    static var seed: URL? {
        Bundle.main.url(forResource: "SeedData", withExtension: nil)
    }
}

extension URL {
    func creationDate() -> Date? {
        // Use FileManager to retrieve the file attributes
        do {
            let fileAttributes = try FileManager.default.attributesOfItem(atPath: self.path())
            
            // Access the creationDate from the file attributes
            if let creationDate = fileAttributes[.creationDate] as? Date {
                print("File creationDate: \(creationDate)")
                return creationDate
            } else {
                print("creationDate not found.")
            }
        } catch {
            print("Error retrieving file attributes: \(error.localizedDescription)")
        }
        
        return nil
    }

    func fftImportingStatus() -> Int? {
        // Read the contents of the file
        guard let fileContents = try? String(contentsOfFile: path(), encoding: .utf8) else {
            return nil
        }
        
        // Split the contents by newline characters
        let lines = fileContents.components(separatedBy: .newlines)
        //0 means no need to reimport, just recalc
        //1 or missing means re-import
        if let line = lines.first(where: {
            $0.hasPrefix("import-status:")
        }) {
            return Int(line.replacingOccurrences(of: "import-status:", with: ""))
        }
        
        return nil
    }
    
    func fftImportingMaleUnrankValue() -> Int? {
        // Read the contents of the file
        guard let fileContents = try? String(contentsOfFile: path(), encoding: .utf8) else {
            return nil
        }
        
        // Split the contents by newline characters
        let lines = fileContents.components(separatedBy: .newlines)
        
        if let line = lines.first(where: {
            $0.hasPrefix("unrank-male-value:")
        }) {
            return Int(line.replacingOccurrences(of: "unrank-male-value:", with: ""))
        }
        
        return nil
    }
    
    func fileModelIdentifier() -> String? {
        // Read the contents of the file
        guard let fileContents = try? String(contentsOfFile: path(), encoding: .utf8) else {
            return nil
        }
        
        // Split the contents by newline characters
        let lines = fileContents.components(separatedBy: .newlines)
        
        if let line = lines.first(where: {
            $0.hasPrefix("file-model-version:")
        }) {
            return line.replacingOccurrences(of: "file-model-version:", with: "")
        }
        
        return nil
    }

    func fftImportingUncomplete() -> Int? {
        // Read the contents of the file
        guard let fileContents = try? String(contentsOfFile: path(), encoding: .utf8) else {
            return nil
        }
        
        // Split the contents by newline characters
        let lines = fileContents.components(separatedBy: .newlines)
        
        if let line = lines.first(where: {
            $0.hasPrefix("max-players:")
        }) {
            return Int(line.replacingOccurrences(of: "max-players:", with: ""))
        }
        
        return nil
    }
    
    func getUnrankedValue() -> Int? {
        // Read the contents of the file
        guard let fileContents = try? String(contentsOfFile: path(), encoding: .utf8) else {
            return nil
        }
        
        // Split the contents by newline characters
        let lines = fileContents.components(separatedBy: .newlines)
        
        // Get the last non-empty line
        var lastLine: String?
        for line in lines.reversed() {
            let trimmedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
            if !trimmedLine.isEmpty {
                lastLine = trimmedLine
                break
            }
        }
        
        guard let rankString = lastLine?.components(separatedBy: ";").dropFirst().first, let rank = Int(rankString) else {
            return nil
        }
        // Define the regular expression pattern
        let pattern = "\\b\(NSRegularExpression.escapedPattern(for: rankString))\\b"
        
        // Create the regular expression object
        guard let regex = try? NSRegularExpression(pattern: pattern) else {
            return nil
        }
        
        // Get the matches
        let matches = regex.matches(in: fileContents, range: NSRange(fileContents.startIndex..., in: fileContents))
        
        // Return the count of matches
        return matches.count + rank - 1
    }
}
