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

import Foundation
import SwiftUI
import LeStorage

@Observable
class MonthData : ModelObject, Storable {
    
    static func resourceName() -> String { return "month-data" }
    static func tokenExemptedMethods() -> [HTTPMethod] { return [] }

    private(set) var id: String = Store.randomId()
    private(set) var monthKey: String
    private(set) var creationDate: Date
    
    var maleUnrankedValue: Int? = nil
    var femaleUnrankedValue: Int? = nil
    var maleCount: Int? = nil
    var femaleCount: Int? = nil
    var anonymousCount: Int? = nil

    
    init(monthKey: String) {
        self.monthKey = monthKey
        self.creationDate = Date()
    }
    
    func total() -> Int {
        return (maleCount ?? 0) + (femaleCount ?? 0)
    }
    
    static func calculateCurrentUnrankedValues(mostRecentDateAvailable: Date) async {
        let lastDataSourceMaleUnranked = await FederalPlayer.lastRank(mostRecentDateAvailable: mostRecentDateAvailable, man: true)
        let lastDataSourceFemaleUnranked = await FederalPlayer.lastRank(mostRecentDateAvailable: mostRecentDateAvailable, man: false)
        let anonymousCount = await FederalPlayer.anonymousCount(mostRecentDateAvailable: mostRecentDateAvailable)
        await MainActor.run {
            if let lastDataSource = DataStore.shared.appSettings.lastDataSource {
                let currentMonthData : MonthData = Store.main.filter(isIncluded: { $0.monthKey == lastDataSource }).first ?? MonthData(monthKey: lastDataSource)
                currentMonthData.maleUnrankedValue = lastDataSourceMaleUnranked?.0
                currentMonthData.maleCount = lastDataSourceMaleUnranked?.1
                currentMonthData.femaleUnrankedValue = lastDataSourceFemaleUnranked?.0
                currentMonthData.femaleCount = lastDataSourceFemaleUnranked?.1
                currentMonthData.anonymousCount = anonymousCount
                do {
                    try DataStore.shared.monthData.addOrUpdate(instance: currentMonthData)
                } catch {
                    Logger.error(error)
                }
            }
        }
    }

    override func deleteDependencies() throws {
    }
    
    enum CodingKeys: String, CodingKey {
        case _id = "id"
        case _monthKey = "monthKey"
        case _creationDate = "creationDate"
        case _maleUnrankedValue = "maleUnrankedValue"
        case _femaleUnrankedValue = "femaleUnrankedValue"
        case _maleCount = "maleCount"
        case _femaleCount = "femaleCount"
        case _anonymousCount = "anonymousCount"
    }
}
