//
//  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 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
    }
}
