import React from 'react';
import './App.scss';
import Sidebar from './Components/Sidebar/Sidebar';
import { IAvailableContainerModel } from './Interfaces/IAvailableContainerModel';
import { IConfigurationResponseModel } from './Interfaces/IConfigurationResponseModel';
import { SVG } from './SVG/SVG';

interface IAppProps {
}

interface IAppState {
  isSidebarOpen: boolean,
  configuration: IConfigurationResponseModel
}

class App extends React.Component<IAppProps> {
  public state: IAppState;

  constructor(props: IAppProps) {
    super(props);
    this.state = {
      isSidebarOpen: true,
      configuration: {
        AvailableContainers: [],
        AvailableSymbols: [],
        MainContainer: {} as IAvailableContainerModel
      }
    };
  }

  componentDidMount() {
    fetchConfiguration().then((configuration: IConfigurationResponseModel) => {
      this.setState({
        isSidebarOpen: this.state.isSidebarOpen,
        configuration
      });
    });
  }

  public ToggleMenu() {
    this.setState({
      isSidebarOpen: !this.state.isSidebarOpen,
      configuration: this.state.configuration
    });
  }

  render() {
    return (
      <div className="App font-sans h-full">
        <Sidebar componentOptions={this.state.configuration.AvailableContainers} isOpen={this.state.isSidebarOpen} onClick={() => this.ToggleMenu()} />
        <button className='fixed z-0 top-4 left-4 text-lg' onClick={() => this.ToggleMenu()}>&#9776; Menu</button>
        <SVG MainContainer={this.state.configuration.MainContainer} />
      </div>
    );
  }
}

async function fetchConfiguration(): Promise<IConfigurationResponseModel> {
  const url = `${import.meta.env.VITE_API_URL}`;
  const myHeaders = new Headers({
    'Content-Type': 'application/json'
  });

  const myInit = {
    method: 'POST',
    headers: myHeaders
  };

  return await fetch(url, myInit)
    .then((response) =>
      response.json()
    ) as IConfigurationResponseModel;
}

export default App;
