using Q42.HueApi;
using Q42.HueApi.Interfaces;
using Q42.HueApi.Models.Bridge;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    private IBridgeLocator bridgeLocator;
    private List<LocatedBridge> bridges;
    private LocatedBridge currentBridge;
    private bool canRunBridgeCheck = true;

    public IReadOnlyList<LocatedBridge> FoundBridges
    {
        get
        {
            if(bridges == null)
            {
                return null;
            }

            return bridges.AsReadOnly();
        }
    }

    public LocatedBridge CurrentBridge
    {
        get
        {
            return currentBridge;
        }
    }

    private void Awake()
    {
        Instance = this;

        if (bridgeLocator == null)
        {
            bridgeLocator = new LocalNetworkScanBridgeLocator();
        }
    }

    private void Start()
    {
        Task.Run(async () =>
        {
            var locatedBridges = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            bridges = locatedBridges.ToList();
        });
    }

    private void LateUpdate()
    {
        if (Time.frameCount % 100 == 0)
        {
            if(canRunBridgeCheck)
            {
                if (bridges != null && bridges.Any())
                {
                    Debug.Log($"I have found {bridges.Count} hue bridge{(bridges.Count > 1 ? "s" : "")}");
                    canRunBridgeCheck = false;
                }
            }
        }
    }

    public void SetCurrentBridge(LocatedBridge bridge)
    {
        currentBridge = bridge;
        Debug.Log($"Set the current selected bridge to: {currentBridge.IpAddress}: {currentBridge.BridgeId}");
    }
}