<?php

namespace VGM\WOBundle\Controller;

use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use VGM\WOBundle\Entity\CUnit;
use VGM\WOBundle\Entity\PlanningTask;
use VGM\WOBundle\Entity\WorkOrder;

class PlanningTaskController extends Controller {
    /**
     * Lists all tasks entities.
     *
     */
    public function PlanningBoardAction()
    {
        return $this->render('VGMWOBundle:Planning:planning_board.html.twig');
    }

    public function getTasksAjaxAction()
    {
        $em = $this->getDoctrine()->getManager();

        $units0 = $em->getRepository('VGMWOBundle:CUnit')->findAllUnits();

        $units_list = [];
        if(count($units0) > 0){
            foreach($units0 as $unit){
                $tasks = $this->generateTasksArray($unit);
                $units_list[] = array('id' => $unit->getId(),
                    'name' => $unit->__toString(),
                    'tasks_open' => $tasks['open'],
                    'tasks_dismissed' => $tasks['dismissed'],
                    'tasks_finished' => $tasks['finished']);
            }
        }

        $response = array("code" => 100, "success" => true, "units" => $units_list, "message" => "Ok");

        return new Response(json_encode($response));
    }

    public function saveTasksAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         * initializing others vars
         */
        $own_id = $request->get('own_id');
        $area = $request->get('area');
        $description = $request->get('description');
        $unit = $request->get('unit_id') ? $em->getRepository('VGMWOBundle:CUnit')->find($request->get('unit_id')) : null;
        $supervisor = $request->get('supervisor_id') ? $em->getRepository('VGMWOBundle:Worker')
                                                             ->find($request->get('supervisor_id')) : null;
        $status = $request->get('status');
        $start_date = $request->get('start_date') ? new \DateTime($request->get('start_date')) : null;
        $etime = $request->get('etime');
        $death_line = $request->get('death_line') ? new \DateTime($request->get('death_line')) : null;
        $obs = $request->get('obs');
        $ended = $request->get('ended') ? new \DateTime($request->get('ended')) : null;
        $rtime = $request->get('rtime');

        $task = null;
        if($own_id == null)
            $task = new PlanningTask();
        $task->setArea($area);
        $task->setDescription($description);
        if($unit != null)
            $task->setUnit($unit);
        if($supervisor != null)
            $task->setSupervisor($supervisor);
        $task->setStatus($status);
        $task->setStartDate($start_date);
        $task->setEtime($etime);
        $task->setDeathLine($death_line);
        $task->setObs($obs);
        $task->setCompletedAt($ended);
        $task->setRtime($rtime);

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

        $response = array("code" => 100, "success" => true, "units" => $units_list, "message" => "Ok");

        return new Response(json_encode($response));
    }
    public function deleteTasksAjaxAction()
    {
        $em = $this->getDoctrine()->getManager();

        $units0 = $em->getRepository('VGMWOBundle:CUnit')->findAllUnits();

        $units_list = [];
        if(count($units0) > 0){
            foreach($units0 as $unit){
                $tasks = $this->generateTasksArray($unit);
                $units_list[] = array('id' => $unit->getId(),
                    'name' => $unit->__toString(),
                    'tasks_open' => $tasks['open'],
                    'tasks_dismissed' => $tasks['dismissed'],
                    'tasks_finished' => $tasks['finished']);
            }
        }

        $response = array("code" => 100, "success" => true, "units" => $units_list, "message" => "Ok");

        return new Response(json_encode($response));
    }

    private function generateChildrenArray($unit){
        $children = [];
        if(count($unit->getChildren()) > 0){
            foreach($unit->getChildren() as $child){
                $tasks = $this->generateTasksArray($child);
                $children[] = array('id' => $child->getId(),
                                    'name' => $child->__toString(),
                                    'units' => $this->generateChildrenArray($child),
                                    'tasks_open' => $tasks['open'],
                                    'tasks_dismissed' => $tasks['dismissed'],
                                    'tasks_finished' => $tasks['finished']);
            }

        }
        return $children;
    }

    private function generateTasksArray(CUnit $unit){
        $tasks = array('open' => [], 'dismissed' => [], 'finished' => []);
        if(count($unit->getTasks()) == 0){
            return $tasks;
        }
        else{
            $em = $this->getDoctrine()->getManager();

            $open = $em->getRepository('VGMWOBundle:PlanningTask')->getTasksByStatus('Open', $unit->getId());
            foreach($open as $t){
                $wos = [];
                foreach($t->getWorkorders() as $wo)
                    $wos[] = $wo->getNumber();

                $tasks['open'][] = array('id' => $t->getId(),
                                         'description' => $t->getDescription(),
                                         'description_full' => $t->getDescriptionFull(),
                                         'workorders' => $wos,
                                         'starts' => $t->getStartDate()->format('m/d/Y'),
                                         'ends' => $t->getDeathLine()->format('m/d/Y'),
                                         'last_update' => $t->getUpdatedAt()->format('m/d/Y'));
            }

            $dismissed = $em->getRepository('VGMWOBundle:PlanningTask')->getTasksByStatus('Dismissed', $unit->getId());
            foreach($dismissed as $t){
                $wos = [];
                foreach($t->getWorkorders() as $wo)
                    $wos[] = $wo->getNumber();

                $tasks['dismissed'][] = array('id' => $t->getId(),
                    'description' => $t->getDescription(),
                    'description_full' => $t->getDescriptionFull(),
                    'workorders' => $wos,
                    'starts' => $t->getStartDate()->format('m/d/Y'),
                    'ends' => $t->getDeathLine()->format('m/d/Y'),
                    'last_update' => $t->getUpdatedAt()->format('m/d/Y'));
            }

            $finished = $em->getRepository('VGMWOBundle:PlanningTask')->getTasksByStatus('Finished', $unit->getId());
            foreach($finished as $t){
                $wos = [];
                foreach($t->getWorkorders() as $wo)
                    $wos[] = $wo->getNumber();

                $tasks['finished'][] = array('id' => $t->getId(),
                    'description' => $t->getDescription(),
                    'description_full' => $t->getDescriptionFull(),
                    'workorders' => $wos,
                    'starts' => $t->getStartDate()->format('m/d/Y'),
                    'ends' => $t->getDeathLine()->format('m/d/Y'),
                    'last_update' => $t->getUpdatedAt()->format('m/d/Y'));
            }

            return $tasks;
        }
    }
} 