//
//  NetworkManager.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 01/03/2024.
//

import Foundation

class NetworkManager {
    static let shared: NetworkManager = NetworkManager()
    
    func removeRankingData(lastDateString: String, fileName: String) {
        let dateString = ["CLASSEMENT-PADEL", fileName,  lastDateString].joined(separator: "-") + ".csv"

        let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
        let destinationFileUrl = documentsUrl.appendingPathComponent("\(dateString)")
        try? FileManager.default.removeItem(at: destinationFileUrl)
    }
    
    func downloadRankingData(lastDateString: String, fileName: String) async throws {
        
        let dateString = ["CLASSEMENT-PADEL", fileName,  lastDateString].joined(separator: "-") + ".csv"

        let documentsUrl: URL = SourceFileManager.shared.rankingSourceDirectory        
        let destinationFileUrl = documentsUrl.appendingPathComponent("\(dateString)")
        let fileURL = URL(string: "https://xlr.alwaysdata.net/static/rankings/\(dateString)")
        
        if FileManager.default.fileExists(atPath: destinationFileUrl.path()) {
            return
        }
        var request = URLRequest(url:fileURL!)
        request.addValue("attachment;filename=\(dateString)", forHTTPHeaderField:"Content-Disposition")
        request.addValue("text/csv", forHTTPHeaderField: "Content-Type")

        let task = try await URLSession.shared.download(for: request)
        if let urlResponse = task.1 as? HTTPURLResponse {
            if urlResponse.statusCode == 200 {
  
                //todo à voir si on en a besoin, permet de re-télécharger un csv si on détecte qu'il a été mis à jour
//                if FileManager.default.fileExists(atPath: destinationFileUrl.path()) {
//                    if let creationDate = try checkFileCreationDate(filePath: task.0.path()), let previousCreationDate = try checkFileCreationDate(filePath: destinationFileUrl.path()) {
//                        print("File creation date:", creationDate)
//                        print("File previous creation date:", previousCreationDate)
//                        if previousCreationDate.isEarlierThan(creationDate) {
//                            try FileManager.default.removeItem(at: destinationFileUrl)
//                        }
//                    }
//                }
                
                try FileManager.default.copyItem(at: task.0, to: destinationFileUrl)
                print("dl rank data ok", lastDateString, fileName)
            } else if urlResponse.statusCode == 404 && fileName == "MESSIEURS" {
                print("dl rank data failed", lastDateString, fileName)
                throw NetworkManagerError.fileNotYetAvailable
            }
        }
    }
    
    func checkFileCreationDate(filePath: String) throws -> Date? {
        let fileManager = FileManager.default
        let attributes = try fileManager.attributesOfItem(atPath: filePath)
        return attributes[.creationDate] as? Date
    }

}
