//
//  SidebarAutoHelpResolver.swift
//  USB Meter
//

import Foundation
import CoreBluetooth

enum SidebarAutoHelpResolver {
    static func activeReason(
        managerState: CBManagerState,
        cloudAvailability: MeterNameStore.CloudAvailability,
        hasLiveMeters: Bool,
        scanStartedAt: Date?,
        now: Date,
        noDevicesHelpDelay: TimeInterval
    ) -> SidebarHelpReason? {
        if managerState == .unauthorized {
            return .bluetoothPermission
        }
        if shouldPromptForCloudSync(cloudAvailability) {
            return .cloudSyncUnavailable
        }
        if hasWaitedLongEnoughForDevices(
            managerState: managerState,
            hasLiveMeters: hasLiveMeters,
            scanStartedAt: scanStartedAt,
            now: now,
            noDevicesHelpDelay: noDevicesHelpDelay
        ) {
            return .noDevicesDetected
        }
        return nil
    }

    private static func shouldPromptForCloudSync(_ cloudAvailability: MeterNameStore.CloudAvailability) -> Bool {
        switch cloudAvailability {
        case .noAccount, .error:
            return true
        case .unknown, .available:
            return false
        }
    }

    private static func hasWaitedLongEnoughForDevices(
        managerState: CBManagerState,
        hasLiveMeters: Bool,
        scanStartedAt: Date?,
        now: Date,
        noDevicesHelpDelay: TimeInterval
    ) -> Bool {
        guard managerState == .poweredOn else {
            return false
        }
        guard hasLiveMeters == false else {
            return false
        }
        guard let scanStartedAt else {
            return false
        }
        return now.timeIntervalSince(scanStartedAt) >= noDevicesHelpDelay
    }
}