import { invoke } from '@tauri-apps/api';
import { FC, useMemo } from 'react';
import { useAsync } from 'react-async-hook';
import { DisplayWithLedStrips } from './components/display-with-led-strips';
import { PickerConfiguration } from './models/picker-configuration';

const getPickerConfig = () => invoke<PickerConfiguration>('get_picker_config');
const getScreenshotOfDisplays = () =>
  invoke<string[]>('take_snapshot').then((items) =>
    items?.map((it) => `data:image/webp;base64,${it}`),
  );

export const Configurator: FC = () => {
  const { loading: pendingPickerConfig, result: pickerConfig } = useAsync(
    getPickerConfig,
    [],
  );

  const { loading: pendingScreenshotOfDisplays, result: screenshotOfDisplays } = useAsync(
    getScreenshotOfDisplays,
    [],
  );

  const displays = useMemo(() => {
    if (pickerConfig && screenshotOfDisplays) {
      return screenshotOfDisplays.map((screenshot, index) => (
        <DisplayWithLedStrips
          key={index}
          config={pickerConfig.display_configs[index] ?? {}}
          screenshot={screenshot}
        />
      ));
    }
  }, [pickerConfig, screenshotOfDisplays]);

  if (pendingPickerConfig || pendingScreenshotOfDisplays) {
    return (
      <section>
        等待 {JSON.stringify({ pendingPickerConfig, pendingScreenshotOfDisplays })}
        {displays}
      </section>
    );
  }

  return <section>{displays}</section>;
};
