import { useEffect, useState } from 'react'
import './App.css'
import LoadingScreen from './LoadingScreen'
import { useFirmwareAPI, useGlobalState } from 'providers'
import { Firmware } from 'models'

interface Props {
  children: any;
}

export default function FirmwareLoader(props: Props) {
  const { children } = props;
  const [loading, setLoading] = useState(false)
  const firmwareAPI = useFirmwareAPI();
  const [global, dispatch] = useGlobalState();

  const loadFirmware = () => {
    setLoading(true)
    firmwareAPI.getAllLatestFirmware().then(resp => {
      let versions: Map<string, Firmware> = new Map();
      if (resp && resp.data && resp.data.firmware) {
        resp.data.firmware.forEach((raw: any) => {
          let firmware = Firmware.any(raw);
          let key = firmware.settings.platform + ":" + firmware.settings.channel;
          versions.set(key, firmware);
        });
      }
      dispatch({ key: "firmware", value: versions });
    }).finally(() => {
      setLoading(false)
    })
  }
  
  useEffect(() => {
    if (loading) return;
    loadFirmware()
  }, [loading])
  
  if (loading || !global) return (
    <LoadingScreen message='Loading firmwares' />
  )

  return (
    <>
    {children}
    </>
  )
}