<?php
/**
 * Created by PhpStorm.
 * User: danielknudsen
 * Date: 05.04.18
 * Time: 13:09
 */
namespace App\Controller;

use App\Entity\DinAsset;
use App\Entity\DinAssetBenchmark;
use App\Entity\DinAssetTask;
use App\Entity\User;
use App\Entity\UserWorksheet;
use App\Entity\UserWorksheetTask;
use App\Repository\UserRepository;
use App\Service\CalculatorService;
use App\Utils\Utils;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;

/**
 * @Security("is_granted('ROLE_USER')")
 */
class UserController extends AbstractController
{

    /**
     * @Route("/start", name="start")
     */
    public function showStart()
    {
        /** @var User $user */
        $user = $this->getUser();

        $worksheets = $user->getWorksheets();
        $cntWorksheets = count($worksheets);
        $numWorksheetsLeft =  $user->getMaxWorksheets() - $cntWorksheets;

        $resWorksheets = $worksheets->toArray();
        usort($resWorksheets, function(UserWorksheet $a, UserWorksheet $b) {
            return $a->getCreationDate() > $b->getCreationDate();
        });

        return $this->render('pages/start.html.twig',
            [
                'worksheets' => $resWorksheets,
                'numWorksheetsLeft' => $numWorksheetsLeft,
            ]
        );
    }

    /**
     * @Route("/risk-analysis", name="risk_analysis")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function showRiskAnalysis()
    {
        $em = $this->getDoctrine()->getManager();

        /** @var User $user */
        $user = $this->getUser();

        $dinAssets = $em->getRepository(DinAsset::class)->findAll();
        /** @var DinAsset $initialDinAsset */
        $initialDinAsset = null;
        $benchmarkValues = [];
        if (count($dinAssets) > 0) {
            $initialDinAsset = $dinAssets[0];
            $benchmarkValues = $initialDinAsset->getBenchMarkSelectValues();
        }

        return $this->render('pages/risk_analysis.html.twig',
            [
                'initialDinAsset' => $initialDinAsset,
                'benchmarkValues' => $benchmarkValues,
                'dinAssets' => $dinAssets,
                'riskFailure' => Utils::$riskFailure,
                'riskCosts' => Utils::$riskCosts,
            ]
        );
    }

    /**
     * @Route("/get-benchmark-data", name="get_benchmark_data")
     */
    public function getBenchmarkData(Request $request)
    {
        $assetId = $request->query->get('assetId');
        /** @var DinAsset $dinAsset */
        $dinAsset = $this->getDoctrine()->getRepository(DinAsset::class)->find($assetId);

        if (null === $dinAsset) {
            return new JsonResponse(null, JsonResponse::HTTP_BAD_REQUEST);
        }

        $res = [];
        $res['cycleMin'] = $dinAsset->getCycleMonthsMin();
        $res['cycleMax'] = $dinAsset->getCycleMonthsMax();
        $res['benchmarkValues'] = $dinAsset->getBenchMarkSelectValues();
        return $this->json($res);
    }

    /**
     * @Route("/calculate-risk", name="calculate_risk")
     */
    public function calculateRisk(Request $request, CalculatorService $calculatorService)
    {
        $params = $request->request->all();
        $benchMark = $this->getDoctrine()->getRepository(DinAssetBenchmark::class)->find($params['benchmark']);
        $res = $calculatorService->calculateRisk($benchMark, $params);
        return $this->json($res);
    }

    /**
     * @Route("/create-worksheet", name="create_worksheet")
     */
    public function createWorksheet(Request $request, CalculatorService $calculatorService)
    {
        /** @var User $user */
        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        if (count($user->getWorksheets()) >= $user->getMaxWorksheets()) {
            return new JsonResponse(null, JsonResponse::HTTP_BAD_REQUEST);
        }
        $params = $request->request->all();
        $benchMark = $em->getRepository(DinAssetBenchmark::class)->find($params['benchmark']);
        $calculation = $calculatorService->calculateRisk($benchMark, $params);

        $benchmark = $em->getRepository(DinAssetBenchmark::class)->find($params['benchmark']);
        /** @var DinAsset $asset */
        $asset = $benchmark->getDinAsset();
        $assetTasks = $asset->getTasks();

        $em->getConnection()->beginTransaction();

        try {
            $worksheet = new UserWorksheet($user);
            $worksheet->setDinNumber($asset->getDinNumber());
            $worksheet->setDinAssetName($asset->getName());
            $worksheet->setFailureProbability(Utils::$riskFailure[$params['failure']][0]);
            $worksheet->setFailureDamage(Utils::$riskCosts[$params['costs']][0]);
            $worksheet->setMaintenanceAdvantage($params['maintenance']);
            $worksheet->setInspectionAdvantage($params['inspection']);
            $worksheet->setUserCycleMonths($params['cycle']);
            $worksheet->setBandwidth($benchmark->getBandwidth());
            $worksheet->setRecMaintenanceCycleMonths($calculation['recCycleMaintenance']);
            $worksheet->setRecInspectionCycleMonths($calculation['recCycleInspection']);
            $worksheet->setDeviationPercentage($calculation['costDiffCurRecPercentage']);
            $worksheet->setDeviationCosts($calculation['costDiffCurCycleRecCycle']);

            $em->persist($worksheet);
            $em->flush();

            /** @var DinAssetTask $assetTask */
            foreach ($assetTasks as $assetTask) {
                $worksheetTask = new UserWorksheetTask();
                $worksheetTask->setUserWorksheet($worksheet);
                $worksheetTask->setDelimitation($assetTask->getDelimitation());
                $worksheetTask->setTask($assetTask->getTask());
                $worksheetTask->setInspection($assetTask->getInspection());
                $worksheetTask->setMaintenance($assetTask->getMaintenance());
                $worksheetTask->setService($assetTask->getService());
                $worksheetTask->setExpert($assetTask->getExpert());
                $worksheetTask->setSpecialist($assetTask->getSpecialist());
                $worksheetTask->setSkilledPersonnel($assetTask->getSkilledPersonnel());
                $worksheetTask->setNorm($assetTask->getNorm());
                $em->persist($worksheetTask);
                $em->flush();
            }
            $em->flush();
            $em->getConnection()->commit();

        } catch (\Exception $e) {
            $em->getConnection()->rollBack();
            return new JsonResponse(null, JsonResponse::HTTP_BAD_REQUEST);
        }

        return new JsonResponse($worksheet->getId(), JsonResponse::HTTP_OK);
    }

    /**
     * @Route("/worksheet/{uuid}", name="show_worksheet")
     */
    public function showWorksheet($uuid)
    {
        /** @var User $user */
        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        /** @var UserWorksheet $worksheet */
        $worksheet = $em->getRepository(UserWorksheet::class)->findOneBy(['id' => $uuid]);

        if (null === $worksheet || $user->getId() !== $worksheet->getUser()->getId()) {
            throw new \Exception('not allowed or not exists');
        }

        return $this->render('pages/worksheet.html.twig',
            [
                'worksheet' => $worksheet,
                'isPdf' => false
            ]
        );
    }

    /**
     * @Route("/download/{uuid}", name="download")
     */
    public function downloadLastCataloguePdf(Environment $twig, $uuid)
    {
        ini_set('max_execution_time', '60');

        /** @var User $user */
        $user = $this->getUser();
        $em = $this->getDoctrine()->getManager();

        /** @var UserWorksheet $worksheet */
        $worksheet = $em->getRepository(UserWorksheet::class)->findOneBy(['id' => $uuid]);

        if (null === $worksheet || $user->getId() !== $worksheet->getUser()->getId()) {
            throw new \Exception('not allowed or not exists');
        }

        $dompdf = UserRepository::renderWorksheetPDF($twig, $worksheet);

        // Output the generated PDF to Browser (force download)
        $fileName = "Arbeitskarte_".$worksheet->getCreationDate()->format('Y-m-d_H-i');
        $dompdf->stream($fileName, [
            "Attachment" => true
        ]);
        // NOTE: This is required, since method need a result!
        exit(0);
    }

    /**
     * @Route("/legal-page", name="legal_page", methods={"GET"})
     */
    public function legalPage()
    {
        return $this->render('pages/legal.html.twig', []);
    }

    /**
     * @Route("/accept-legal-terms", name="accept_legal_terms", methods={"GET"})
     */
    public function acceptlegalTerms()
    {
        /** @var User $user */
        $user = $this->getUser();
        if ($user) {
            $user->setAcceptedLegal(true);
            $user->setAcceptedTerms(true);
            $this->getDoctrine()->getManager()->flush();
            return $this->redirectToRoute('start');
        }
        return $this->redirectToRoute('index');
    }
}