<?php

namespace {{ controllerNamespaceDir }};

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Ast\EasyPanelBundle\Lib\Easy\EasyList;
use Ast\EasyPanelBundle\Lib\Easy\EasyShow;
use Ast\EasyPanelBundle\Lib\Easy\EasyForm;
use Ast\EasyPanelBundle\Lib\Easy\Panel;
use Ast\EasyPanelBundle\Services\EasyPanelService;

use {{ entityNamespace }};
use {{ formNamespace }};
use {{ repoNamespace }};


/**
 * @Route("{{ prefix_route_controller }}" )
 */
class {{ entity }}Controller extends AbstractController
{

    /**
     * @return array
     */
    private function fields($type = 'fields'){
        $matrix = [
            'fields' => ['{{ indexlist|join("', '")|raw }}'],
            'headers' =>['{{ indexlistLabel|join("', '")|raw }}'],
            'search' => ['{{ indexlist|join("', '")|raw }}'],
            'show' => ['{{ showlist|join("', '")|raw }}'],
            'headerShow' => ['{{ showlistLabel|join("', '")|raw }}']
            ];
        return isset($matrix[$type])?$matrix[$type]:[];
    }

    private function getRepository(){
        $em = $this->getDoctrine()->getManager();
        return new {{ entity }}Repository($em, $em->getClassMetadata({{ entity }}::class));
    }

    /**
     *List All {{ entity }} entity
     *
{% if panelTypeHtml == panelType %}
     * @Route("/", methods={"GET","HEAD"}, name="{{ prefix_route_name }}_index" )
{% elseif panelTypeApi == panelType %}
     * @Route("/", methods={"GET","HEAD"}, name="{{ prefix_route_name }}_index" )
{% endif %}
     */
    public function indexAction(Request $request{{ serviceautowire }})
    {
        {{ '$this->' }}get('session')->set('menu-active', '{{ entityLower }}');

        $buscar = $request->get('buscar', '');
        $pagina = $request->get('pagina', 1);
        $col = $request->get('columna', 0);
        $orden = $request->get('orden', 'ASC');

        $result = $this->getRepository()->listEasy($buscar,$pagina,$col,$orden,$this->fields(),$this->fields('search'));

{% if panelTypeHtml == panelType %}
        $view = EasyList::easy('{{ seccion }}', $result, $this->fields() );
        $view->defaultConfigList('{{ prefix_route_name }}', $this->fields('headers'),'{{ prefix_route_name }}_index',$buscar,$col,$orden);
        return {{ serviceincontroller|raw }}->render($view);
{% elseif (panelTypeApi == panelType) %}
        $view = EasyList::easy('{{ entityLower }}', $result, $this->fields() );
        return {{ serviceincontroller|raw }}->json($view);
{% endif %}
        
    }

    /**
     * Create a new {{ entity }} entity.
     *
{% if panelTypeHtml == panelType %}
     * @Route("/new", methods={"GET","HEAD","POST"}, name="{{ prefix_route_name }}_new")
{% elseif panelTypeApi == panelType %}
     * @Route("/new", methods={"HEAD","POST"}, name="{{ prefix_route_name }}_new")
{% endif %}
     */
    public function nuevoAction(Request $request{{ serviceautowire }})
    {
{% if panelTypeHtml == panelType %}
        ${{ entityLower }} = new {{ entity }}();
        $form = $this->createForm({{ formName }}::class, ${{ entityLower }});
        if($request->getMethod()=='POST'){
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                return $this->saveForm(${{ entityLower }});
            }else{
                $this->addFlash('warning','Debes ingresar los datos correctamente');
            }
        }
        $easyForm = EasyForm::easy('Nuevo {{ seccion }}', $form->createView());
        $easyForm->defaultConfigForm('{{ prefix_route_name }}_index',[]);
        return {{ serviceincontroller|raw }}->render($easyForm);
{% elseif panelTypeApi == panelType %}
        $dataRequest = json_decode($request->getContent(),true);
        ${{ entityLower }} = new {{ entity }}();
        $form = $this->createForm({{ formName }}::class, ${{ entityLower }});
        $form->submit($dataRequest);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->getRepository()->save(${{ entityLower }});
            $json = Panel::easyShowApi('{{ entity }}',${{ entityLower }},$this->fields('show'));
            $status = 200;
        }else{
            $json = ['code'=>false,'message'=>'Debes ingresar los datos correctamente','data'=>[]];
            $status = 400;
        }
        return $this->json($json,$status);
{% endif %}
    }

    /**
     * Finds and displays a {{ entity }} entity.
     *
     * @Route("/{id}", methods={"GET","HEAD"}, name="{{ prefix_route_name }}_show", requirements={"id"="\d+"} )
     */
    public function showAction(int $id{{ serviceautowire }})
    {
        ${{ entityLower }} = $this->getRepository()->getById($id);
{% if panelTypeHtml == panelType %}
        $show = EasyShow::easy('Ver {{ seccion }}', ${{ entityLower }}, $this->fields('show'));
        $show->defaultConfigShow('{{ prefix_route_name }}',$this->fields('headerShow'),$this->generateDeleteForm(${{ entityLower }})->createView());
        return {{ serviceincontroller|raw }}->render($show);
{% elseif panelTypeApi == panelType %}
        $show = EasyShow::easy('{{ entityLower }}', ${{ entityLower }}, $this->fields('show'));
        $show->setLabelsFields($this->fields('headerShow'));
        return {{ serviceincontroller|raw }}->json($show);
{% endif %}
    }

    /**
     * Displays a form to edit an existing {{ entity }} entity.
{% if panelTypeHtml == panelType %}
     * @Route("/{id}/edit", methods={"GET","HEAD","POST"}, name="{{ prefix_route_name }}_edit", requirements={"id"="\d+"})
{% elseif panelTypeApi == panelType %}
     * @Route("/{id}/edit", methods={"HEAD","POST"}, name="{{ prefix_route_name }}_edit", requirements={"id"="\d+"})
{% endif %}
     */
    public function editAction(Request $request, int $id{{ serviceautowire }})
    {
        $olds = [];
{% for key,campo in propertysEntity %}
{% if campo in ['thumb','imagen','poster','foto','video','pdf','archivo','metaimage','imagenpreview','metaimagelarge'] %}
        $olds['{{ campo }}'] = ${{ entityLower }}->get{{ campo|capitalize }}();
{% endif %}
{% endfor %}
        ${{ entityLower }} = $this->getRepository()->getById($id);

{% if panelTypeHtml == panelType %}
        $editForm = $this->createForm({{ formName }}::class, ${{ entityLower }});
        if($request->getMethod()=='POST'){
            $editForm->handleRequest($request);
            if ($editForm->isSubmitted() && $editForm->isValid()) {
                return $this->saveForm(${{ entityLower }},$olds);
            }else{
                $this->addFlash('warning','Debes ingresar los datos correctamente');
            }
        }
        $easyForm = EasyForm::easy('Editar {{ entity }}', $editForm->createView());
        $easyForm->defaultConfigForm('{{ prefix_route_name }}_show',['id'=>${{ entityLower }}->getId()],$this->generateDeleteForm(${{ entityLower }})->createView());
        return {{ serviceincontroller|raw }}->render($easyForm);
{% elseif panelTypeApi == panelType %}
        if(${{ entityLower }}){
            $editForm = $this->createForm({{ formName }}::class, ${{ entityLower }});
            $dataRequest = json_decode($request->getContent(),true);
            $editForm->submit($dataRequest);
            if ($editForm->isSubmitted() && $editForm->isValid()) {
                $this->getRepository()->save(${{ entityLower }});
                $json = Panel::easyShowApi('{{ entity }}',${{ entityLower }},$this->fields('show'));
                $status = 200;
            }else{
                $json = ['code'=>false,'message'=>'Debes ingresar los datos correctamente','data'=>[]];
                $status = 400;
            }
        }else{
            $json = ['code'=>false,'message'=>'El recurso que buscas no se encuentra','data'=>[]];
            $status = 404;
        }
        return $this->json($json, $status);
{% endif %}
    }

    /**
     * Deletes a {{ entity }} entity.
     *
{% if panelTypeHtml == panelType %}
     * @Route("/{id}/delete", methods={"HEAD","DELETE"}, name="{{ prefix_route_name }}_delete", requirements={"id"="\d+"})
{% elseif panelTypeApi == panelType %}
    * @Route("/{id}/delete", methods={"HEAD","POST"}, name="{{ prefix_route_name }}_delete", requirements={"id"="\d+"})
{% endif %}
     */
    public function deleteAction(Request $request, int $id)
    {
        ${{ entityLower }} = $this->getDoctrine()->getManager()->getRepository({{entity}}::class)->findOneBy(['id'=>$id]);
{% if panelTypeHtml == panelType %}
        $form = $this->generateDeleteForm(${{ entityLower }});
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
{% for key,campo in propertysEntity %}
{% if campo in ['thumb','imagen','poster','foto','video','pdf','archivo','metaimage','imagenpreview','metaimagelarge'] %}
            $this->deleteMedia(${{ entityLower }}->get{{ campo|capitalize }}());
{% endif %}
{% endfor %}
            $this->getRepository()->deleteByObject(${{ entityLower }});
            $this->addFlash('warning','{{ entity }} eliminado correctamente');
        }
        return $this->redirectToRoute('{{ prefix_route_name }}_index');
{% elseif panelTypeApi == panelType %}
        if(${{ entityLower }}){
{% for key,campo in propertysEntity %}
{% if campo in ['thumb','imagen','poster','foto','video','pdf','archivo','metaimage','imagenpreview','metaimagelarge'] %}
            $this->deleteMedia(${{ entityLower }}->get{{ campo|capitalize }}());
{% endif %}
{% endfor %}
            $this->getRepository()->deleteByObject(${{ entityLower }});
            $json = ['code'=>true,'message'=>'{{ entity }} eliminada correctamente','data'=>[]];
            $status = 200;
        }else{
            $json = ['code'=>false,'message'=>'{{ entity }} no existe','data'=>[]];
            $status = 400;
        }
        return $this->json($json, $status);
{% endif %}
    }

    /**
     * @param {{ entity }} ${{ entityLower }}
     * @param array|null $olds
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    private function saveForm( {{ entity }} ${{ entityLower }}, array $olds = null){

        $em = $this->getDoctrine()->getManager();
{% for key,campo in propertysEntity %}
{% if campo in ['thumb','imagen','poster','foto','video','pdf','archivo','metaimage','imagenpreview','metaimagelarge'] %}
        if (${{ entityLower }}->get{{ campo|capitalize }}() !== null) {
            ${{ campo }} = ${{ entityLower }}->get{{ campo|capitalize }}();
            $new{{ campo }} = md5(microtime().'{{ key }}') .'.'.${{ campo }}->guessExtension();
            ${{ campo }}->move($this->getPublicUploads(), $new{{ campo }} );
            ${{ entityLower }}->set{{ campo|capitalize }}($new{{ campo }});
            if(isset($olds['{{ campo }}'])){ $this->deleteMedia($olds['{{ campo }}']); }
        }else{
            if(isset($olds['{{ campo }}'])){ ${{ entityLower }}->set{{ campo|capitalize }}($olds['{{ campo }}']); }
        }
{% endif %}
{% endfor %}
{% if  entity == "Administrador" %}
        /**
         * Este fragmento solo se debera de usar para crear el primer administrador
         * Se deberia borrar y configurar correctamente en otro controlador
         */
        if( $olds == null ){
            $salt = \Ast\CustomPassword\BuildPassword::randomSalt();
            $newpass = \Ast\CustomPassword\BuildPassword::create($administrador->getPass(),$salt);
            $administrador->setPass($newpass);
            $administrador->setSalt($salt);
        }
{% endif %}
        $em->persist(${{ entityLower }});
        $em->flush();
        if( $olds == null ){
            $this->addFlash('success','{{ entity }} registrado correctamente');
            return $this->redirectToRoute('{{ prefix_route_name }}_show', array('id'=>${{ entityLower }}->getId()));
        }else{
            $this->addFlash('info','{{ entity }} actualizado correctamente');
            return $this->redirectToRoute('{{ prefix_route_name }}_index', []);
        }
    }

    /**
     * @param {{ entity }} ${{ entityLower }}
     * @return \Symfony\Component\Form\FormInterface
     */
    private function generateDeleteForm({{ entity }} ${{ entityLower }})
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('{{ prefix_route_name }}_delete', ['id' => ${{ entityLower }}->getId()]))
            ->setMethod('DELETE')
            ->getForm();
    }

    /**
     * @return string
     */
    protected function getPublicUploads(){
        if($this->container->hasParameter('public_dir_uploads')){
            $publicdir = $this->getParameter('public_dir_uploads');
        }else{
            $publicdir = $this->getParameter("kernel.root_dir").'{{ pathPublicUploads }}';
        }
        if(!file_exists($publicdir)){
            mkdir($publicdir,0777,true);
        }
        return $publicdir;
    }

    /**
     * @param $file
     */
    protected function deleteMedia($file){
        if(!empty($file)){
            $filename = $this->getPublicUploads().'/'.$file;
            if(file_exists($filename)){
                unlink($filename);
            }
        }
    }



}
