import { NextFunction, Request, Response } from "express";
import { autowired } from "first-di";
import { async } from "node-stream-zip";
import { EntityRepository } from "../../core/repository/entity_repository";
import { IFile } from "./model/zip_files_model";

export class AssemblyController {
  @autowired()
  private readonly entityRepository: EntityRepository;

  public createRootEntity = (
    req: Request,
    res: Response,
    next: NextFunction
  ) => {
    const file = req.files;
    const cadFile = file["freecad"] as IFile;

    this.entityRepository.saveRootEntity(cadFile.data, cadFile.name);

    res.status(200).json("ok");
    return;
  };

  public getAllAssembly = (
    req: Request,
    res: Response,
    next: NextFunction
  ): void => { };

  public createAssembly = (
    req: Request,
    res: Response,
    next: NextFunction
  ): void => {
    try {
      const file = req.files.freecad as IFile;
      const buffer = file.data as Buffer;
      this.entityRepository.saveRootEntity(file.data, file.name);
      res.sendStatus(200);
    } catch (error) {
      next(error);
    }
  };


  public test = (req: Request,
    res: Response,
    next: NextFunction) => {
    try {
      const file = req.files;

      const generation = file["zip"] as IFile;
      const id = 'cubes';

      this.entityRepository.saveGeration(generation.data, id)
      res.sendStatus(200);
    } catch (error) {
      next(error);
    }
  }

  public stabilityComputed = async (
    req: Request,
    res: Response,
    next: NextFunction
  ) => {
    try {
      // const file = req.files;
      console.log(req.body)
      const id = req.body.id;
      // console.log(req.query.id)
      const buildNumber = req.body.buildNumber;
      console.log(buildNumber)
      console.log(id)
      // const generation = file["zip"] as IFile;
      // const id = 'cubes';

      await this.entityRepository.computedStability(id, buildNumber)
      res.sendStatus(200);
    } catch (error) {
      next(error);
    }
  }

  public stabilityCreate = (
    req: Request,
    res: Response,
    next: NextFunction
  ) => {
    try {
      const files = req.files;
      const zip = files['zip'] as IFile
      const query = req.query as any
      this.entityRepository.saveStability(zip.data, query.id, query.buildNumber)
      res.sendStatus(200);
    } catch (error) {
      next(error);
    }
  }
}
