<?php

namespace App\Controller;

use App\Entity\Billing;
use App\Form\BillingType;
use App\Service\BillingService;
use App\Service\DataGrid\DataGrid;
use App\Service\DataGrid\DataGridAggregate;
use App\Service\DataGrid\DataGridFilterMultiselect;
use App\Service\DataGrid\DataGridFilterSingleselect;
use App\Service\DataGrid\DataGridHeader;
use App\Service\DataGrid\DataGridNavigation;
use App\Service\DataGrid\DataGridSort;
use App\Tools\DBAL\EnumBillingStatusType;
use Doctrine\ORM\EntityNotFoundException;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use Limenius\Liform\Liform;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class BillingController extends FOSRestController
{
    private $service;

    public function __construct(BillingService $service)
    {
        $this->service = $service;
    }

    /**
     * Retrieves a collection of Billing resource.
     *
     * @Rest\Get("/billing/grid")
     * @Rest\View(serializerGroups={"grid"})
     *
     * @param Request $request
     *
     * @return View
     */
    public function getGridAction(Request $request): View
    {
        $dataGrid = new DataGrid();

        $dataGrid
            ->setName('Billing')
            ->addHeader(new DataGridHeader(['label' => 'Link', 'id' => 'link', 'isSortable' => true, 'type' => 'link']))
            ->addHeader(new DataGridHeader(['label' => 'Prospect', 'id' => 'link', 'isSortable' => true, 'type' => 'prospect_payment']))
            ->addHeader(new DataGridHeader(['label' => 'Cost', 'id' => 'cost', 'isSortable' => true, 'type' => 'money']))
            ->addHeader(new DataGridHeader(['label' => 'Due Date', 'id' => 'dueDate', 'isSortable' => true, 'type' => 'date']))
            ->addHeader(new DataGridHeader(['label' => 'Paid Date', 'id' => 'paidDate', 'isSortable' => true, 'type' => 'datetime']))
            ->addHeader(new DataGridHeader(['label' => 'Status', 'id' => 'status', 'isSortable' => true]));

        $dataGrid->setNavigation(new DataGridNavigation(['page' => $request->get('page'), 'rpp' => $request->get('rpp')]));

        $dataGrid->addSorter(new DataGridSort(['sort' => $request->get('sort'), 'order' => $request->get('order')]));

        $dataGrid->addFilter(new DataGridFilterSingleselect(
            'status',
            EnumBillingStatusType::getValues(),
            null !== $request->get('status') ? filter_var($request->get('status'), FILTER_VALIDATE_BOOLEAN) : null));

        $dataGrid->addFilter(new DataGridFilterMultiselect(
            'link',
            [],
            $request->get('link') ?? []));

        $dataGrid->addFilter(new DataGridFilterMultiselect(
            'prospect',
            [],
            $request->get('prospect') ?? []));

        $dataGrid->addFilter(new DataGridFilterMultiselect(
            'campaign',
            [],
            $request->get('campaign') ?? []));

        if ($request->get('aggr')) {
            foreach ($request->get('aggr') as $id) {
                $value = $request->get($id);
                $params = explode(':', $value);
                if (2 === count($params)) {
                    list($field, $function) = $params;
                    $groupBy = '';
                } elseif (3 === count($params)) {
                    list($field, $function, $groupBy) = $params;
                }
                $dataGrid->addAggregate(new DataGridAggregate($id, $function, $field, $groupBy));
            }
        }

        $dataGrid->setData($this->service->getByGrid($dataGrid))
            ->setTotal($this->service->countByGrid($dataGrid))
            ->setAggregates($this->service->aggregateByGrid($dataGrid)[0]);

        return View::create($dataGrid, Response::HTTP_OK);
    }

    /**
     * Retrieves a collection of Billing resource.
     *
     * @Rest\Get("/billing")
     *
     * @return View
     */
    public function getAllAction(): View
    {
        $items = $this->service->getAll();

        return View::create($items, Response::HTTP_OK);
    }

    /**
     * Retrieves an Billing resource.
     *
     * @Rest\Get("/billing/{id}", requirements={"id"="\d+"}))
     *
     * @param int $id
     *
     * @return View
     */
    public function getAction(int $id): View
    {
        try {
            $billing = $this->service->get($id);

            return View::create($billing, Response::HTTP_OK);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }
    }

    /**
     * Creates an Billing resource.
     *
     * @Rest\Post("/billing")
     *
     * @param Request $request
     *
     * @return View
     */
    public function postAction(Request $request): View
    {
        $form = $this->createForm(BillingType::class, null, ['csrf_protection' => false]);
        $form->submit($request->request->all());

        if ($form->isSubmitted() && $form->isValid()) {
            $billing = $this->service->save($form->getData());

            return View::create($billing, Response::HTTP_OK);
        }

        return View::create($form, Response::HTTP_BAD_REQUEST);
    }

    /**
     * Replaces Billing resource.
     *
     * @Rest\Put("/billing/{id}")
     *
     * @param Request $request
     * @param int     $id
     *
     * @return View
     */
    public function putAction(Request $request, int $id): View
    {
        try {
            $billing = $this->service->get($id);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }

        $form = $this->createForm(BillingType::class, $billing, ['csrf_protection' => false]);
        $form->submit($request->request->all());

        if ($form->isSubmitted() && $form->isValid()) {
            $billing = $this->service->save($form->getData());

            return View::create($billing, Response::HTTP_OK);
        }

        return View::create($form, Response::HTTP_BAD_REQUEST);
    }

    /**
     * Updates Billing resource.
     *
     * @Rest\Patch("/billing/{id}")
     *
     * @param Request $request
     * @param int     $id
     *
     * @return View
     */
    public function patchAction(Request $request, int $id): View
    {
        try {
            $billing = $this->service->get($id);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }

        $form = $this->createForm(BillingType::class, $billing, ['csrf_protection' => false]);
        $form->submit($request->request->all(), false);

        if ($form->isSubmitted() && $form->isValid()) {
            $billing = $this->service->save($form->getData());

            return View::create($billing, Response::HTTP_OK);
        }

        return View::create($form, Response::HTTP_BAD_REQUEST);
    }

    /**
     * Removes the Billing resource.
     *
     * @Rest\Delete("/billing/{id}")
     *
     * @param int $id
     *
     * @return View
     */
    public function deleteAction(int $id): View
    {
        try {
            $billing = $this->service->get($id);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_BAD_REQUEST, 'message' => $e->getMessage()], Response::HTTP_BAD_REQUEST);
        }

        $this->service->delete($billing);

        return View::create([], Response::HTTP_NO_CONTENT);
    }

    /**
     * Return serialized form to create resource.
     *
     * @Rest\Get("/billing/schema")
     *
     * @param Liform $liform
     *
     * @return View
     */
    public function getSchemaAction(Liform $liform): View
    {
        $billing = new Billing();

        $form = $this->createForm(BillingType::class, $billing, ['csrf_protection' => false]);

        $form = $liform->transform($form);

        return View::create($form, Response::HTTP_OK);
    }
}
