import { useEffect } from "react";
import { useState } from "react";
import { useQuery } from "react-query";
import Layout from "../components/Layout.js";
import Modal from "../components/Modal.jsx";
import PdfForm from "../components/pdf_gen/PdfForm.jsx";
import SelectExo from "../components/pdf_gen/selectExo.jsx";
import {
  getPublicExos,
  getTags,
  getUserExos,
  pdfGen,
} from "../requests/requests.exos.js";
import { notificationService } from "../services/notification.service.js";
import styles from "../styles/pdf_gen/fiche.module.scss";
import { parseClassName } from "../utils/utils.js";

export default function Fiche() {
  /* const { isLoading, isError, data, isFetching } = useQuery(
    ["exo-data"],
    async () =>
      await getUserExos("pdf").then((res) => {
        return {
          ...res,
          results: [
            ...res.results.map((r) => {
              return { ...r, numberInExo: 10, numberOfExo: 1 };
            }),
          ],
        };
      }),
    {
      refetchOnWindowFocus: false,
      keepPreviousData: true,
    }
  ); */

  const generateFile = (content, fileName) => {
    const byteCharacters = atob(content);

    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    const blob = new Blob([byteArray], { type: "application/pdf" });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
  };
  const [exosList, setExos] = useState([]);
  
  const [selected, setSelected] = useState([]);
  const [charging, setCharging] = useState(false);
  const [empty, setEmpty] = useState(false);
  return (
    <Layout page="Composition de fiches">
      <div className={styles["main-container"]}>
        <SelectExo
          exos={exosList}
          setExos={setExos}
          emptyError={empty}
        />
        <div className={styles.form}>
          <PdfForm
            submit={(param) => {
              /* var exosSend = exosList
                .filter((e) => {
                  return selected.includes(e.id_code);
                })
                .sort((a, b) => {
                  return (
                    selected.indexOf(a.id_code) - selected.indexOf(b.id_code)
                  );
                }); */
              setCharging(true);
              /* exosSend = exosSend.map((s) => {
                return {
                  numberInExo: s.numberInExo,
                  numberOfExo: s.numberOfExo,
                  exo_model: s.exo_model,
                  model_type: s.model_type,
                  consigne: s.consigne,
                  id_code: s.id_code,
                };
              }); */
              var exosSend = exosList.reduce((res, current) => {
                return res.concat(
                  Array(parseInt(current.numberOfExo)).fill(current)
                );
              }, []);
              console.log('EXOS RO', exosSend)
              if (exosSend.length == 0) {
                setEmpty(true);
                setCharging(false);
                return;
              }
              pdfGen({
                exos: exosSend,
                file: param.name !== "" ? param.name : "untitled.pdf",
                police: param.police != "" ? param.police + "pt" : 14 + "pt",
                title: param.entete,
              }).then((res) => {
                generateFile(res.data.pdf, res.data.filename);
                setCharging(false);
              }).catch((err) => {
                setCharging(false)
                notificationService.error('Erreur', 'Erreur lors de la génération !')
              }); 
            }}
          />{" "}
        </div>
      </div>
      {charging && (
        <>
          <div className="overlay"></div>
          <div className="loader-big"></div>
        </>
      )}
    </Layout>
  );
}

/* export async function getStaticProps() {
  const exos = await getExos('pdf');
  const tags = await getTags();
  return {
    props: {
      exos: exos,
      tags: tags,
    },
    revalidate: 60,
  };
}
 */
