//
//  MonthData.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 18/04/2024.
//

import Foundation
import SwiftUI
import LeStorage

@Observable
final class MonthData: BaseMonthData {

    init(monthKey: String) {
        super.init()
        self.monthKey = monthKey
        self.creationDate = Date()
    }
    
    required init(from decoder: Decoder) throws {
        try super.init(from: decoder)
    }
    
    required public init() {
        super.init()
    }
    
    func total() -> Int {
        return (maleCount ?? 0) + (femaleCount ?? 0)
    }
    
    static func calculateCurrentUnrankedValues(fromDate: Date) async {
        
        let fileURL = SourceFileManager.shared.allFiles(true).first(where: { $0.dateFromPath == fromDate && $0.index == 0 })
        print("calculateCurrentUnrankedValues", fromDate.monthYearFormatted, fileURL?.path())
        let fftImportingUncomplete = fileURL?.fftImportingUncomplete()
        let fftImportingMaleUnrankValue = fileURL?.fftImportingMaleUnrankValue()

        let incompleteMode = fftImportingUncomplete != nil

        let lastDataSourceMaleUnranked = await FederalPlayer.lastRank(mostRecentDateAvailable: fromDate, man: true)
        let lastDataSourceFemaleUnranked = await FederalPlayer.lastRank(mostRecentDateAvailable: fromDate, man: false)
        let anonymousCount = await FederalPlayer.anonymousCount(mostRecentDateAvailable: fromDate)
        await MainActor.run {
            let lastDataSource = URL.importDateFormatter.string(from: fromDate)
            let currentMonthData : MonthData = DataStore.shared.monthData.first(where: { $0.monthKey == lastDataSource }) ?? MonthData(monthKey: lastDataSource)
            currentMonthData.dataModelIdentifier = PersistenceController.getModelVersion()
            currentMonthData.fileModelIdentifier = fileURL?.fileModelIdentifier()
            currentMonthData.maleUnrankedValue = incompleteMode ? fftImportingMaleUnrankValue : lastDataSourceMaleUnranked?.0
            currentMonthData.incompleteMode = incompleteMode
            currentMonthData.maleCount = incompleteMode ? fftImportingUncomplete : lastDataSourceMaleUnranked?.1
            currentMonthData.femaleUnrankedValue = lastDataSourceFemaleUnranked?.0
            currentMonthData.femaleCount = lastDataSourceFemaleUnranked?.1
            currentMonthData.anonymousCount = anonymousCount
            DataStore.shared.monthData.addOrUpdate(instance: currentMonthData)
            
        }
    }
    
}
