import type { NextPage } from 'next'
import Head from 'next/head'
import {useGroups} from "../../components/contexts/GroupProvider";
import {useFactories} from "../../src/hooks/useFactories";
import {ProducingGraph, ProducingNode} from "../../components/shared/ProducingGraph";
import {useMemo} from "react";
import {calculateInputs} from "../../src/calculateInputs";

const Page: NextPage = () => {
  const {
    exportedFactories,
    ignoredFactories,
    baseFactories,
    groups
  } = useGroups()
  const {
    findFactory
  } = useFactories()

  const producingNodes: ProducingNode[] = useMemo(() => {
    return Object.values(groups).map(group => ({
      inputs: calculateInputs(
        [...group.exports, ...group.malls],
        ignoredFactories,
        baseFactories,
        exportedFactories,
        findFactory
      )[0],
      outputs: group.exports,
      name: group.name,
      icons: [...group.exports, ...group.malls],
      linkOut: `./visualize/${fixedEncodeURIComponent(group.name)}`
    }))
  }, [baseFactories, exportedFactories, findFactory, groups, ignoredFactories])

  return (
    <div>
      <Head>
        <title>Factorio Microservices</title>
        <meta name="description" content="Create Factorio microservices" />
        <link rel="icon" href="/public/favicon.ico" />
      </Head>
      <main>
        <h1>Factorio Microservices</h1>
        <ProducingGraph nodes={producingNodes} inputs={baseFactories}></ProducingGraph>
      </main>
    </div>
  )
}

function fixedEncodeURIComponent(str: string): string {
  return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16));
}


export default Page
