<?php

/* * ********************************************************************************** */
/*      This file is part of the "Diaporamas" Thelia 2 module.                       */
/*                                                                                   */
/*      Copyright (c) OpenStudio                                                     */
/*      email : dev@thelia.net                                                       */
/*      web : http://www.thelia.net                                                  */
/*                                                                                   */
/*      For the full copyright and license information, please view the LICENSE.txt  */
/*      file that was distributed with this source code.                             */
/* * ********************************************************************************** */

namespace ArtabanMarketplace\Controller;

use ArtabanMarketplace\Controller\Base\SellerImageController as BaseSellerImageController;
use ArtabanMarketplace\Event\AmpSellerImageEvent;
use ArtabanMarketplace\Event\AmpSellerImageEvents;
use ArtabanMarketplace\Event\AmpSellerEvent;
use ArtabanMarketplace\Model\AmpSellerImage;
use ArtabanMarketplace\Model\AmpSellerImageQuery;
use Propel\Runtime\Exception\PropelException;
use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Log\Tlog;
use Thelia\Tools\URL;

/**
 * Class SellerImageController
 * @package ArtabanMarketplace\Controller
 */
class SellerImageController extends BaseSellerImageController {

    /**
     * Load a object for modification, and display the edit template.
     *
     * @return \Thelia\Core\HttpFoundation\Response the response
     */
    public function updateAction() {
        // Check current user authorization
//        if (null !== $response = $this->checkAuth($this->resourceCode, $this->getModuleCode(), AccessManager::UPDATE)) {
//            return $response;
//        }

        $image = $this->getExistingObject();

        if (is_null($image)) {
            return $this->pageNotFound();
        }

        $redirectUrl = $image->getRedirectionUrl();

        return $this->render('seller-image-edit', array(
                    'seller_image_id' => $image->getId(),
                    'redirectUrl' => $redirectUrl
        ));
    }
    
/**
     * Save changes on a modified object, and either go back to the object list, or stay on the edition page.
     *
     * @return \Thelia\Core\HttpFoundation\Response the response
     */
    public function processUpdateAction()
    {
        // Check current user authorization
//        if (null !== $response = $this->checkAuth($this->resourceCode, $this->getModuleCode(), AccessManager::UPDATE)) {
//            return $response;
//        }

        // Error (Default: false)
        $error_msg = false;

        // Create the Form from the request
        $changeForm = $this->getUpdateForm($this->getRequest());

        try {
            // Check the form against constraints violations
            $form = $this->validateForm($changeForm, "POST");

            // Get the form field values
            $data = $form->getData();

            // Create a new event object with the modified fields
            $changeEvent = $this->getUpdateEvent($data);
            $changeEvent->bindForm($form);

            // Dispatch Update Event
            $this->dispatch($this->updateEventIdentifier, $changeEvent);

            // Check if object exist
            if (! $this->eventContainsObject($changeEvent)) {
                throw new \LogicException(
                    $this->getTranslator()->trans("No %obj was updated.", ['%obj' => $this->objectName])
                );
            }

            // Log object modification
            if (null !== $changedObject = $this->getObjectFromEvent($changeEvent)) {
                $this->adminLogAppend(
                    $this->resourceCode,
                    AccessManager::UPDATE,
                    sprintf(
                        "%s %s (ID %s) modified",
                        ucfirst($this->objectName),
                        $this->getObjectLabel($changedObject),
                        $this->getObjectId($changedObject)
                    ),
                    $this->getObjectId($changedObject)
                );
            }

            // Execute additional Action
            $response = $this->performAdditionalUpdateAction($changeEvent);

            if ($response == null) {
                // If we have to stay on the same page, do not redirect to the successUrl,
                // just redirect to the edit page again.
                if ($this->getRequest()->get('save_mode') == 'stay') {
                    return $this->redirectToEditionTemplate($this->getRequest());
                }

                // Redirect to the success URL
                return $this->generateSuccessRedirect($changeForm);
            } else {
                return $response;
            }
        } catch (FormValidationException $ex) {
            // Form cannot be validated
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
        /*} catch (\Exception $ex) {
            // Any other error
            $error_msg = $ex->getMessage();*/
        }

        if (false !== $error_msg) {
            // At this point, the form has errors, and should be redisplayed.
            $this->setupFormErrorContext(
                $this->getTranslator()->trans("%obj modification", ['%obj' => $this->objectName]),
                $error_msg,
                $changeForm,
                $ex
            );

            return $this->renderEditionTemplate();
        }
    }


    /**
     * Put in this method post object update processing if required.
     *
     * @param  AmpSellerImageEvent  $updateEvent the update event
     * @return Response a response, or null to continue normal processing
     */
    protected function performAdditionalUpdateAction($updateEvent) {
        if ($updateEvent->getAmpSellerImage() !== NULL) {
            $this->updateImageFile($updateEvent->getAmpSellerImage());
        }
        return null;
    }

    /**
     * Updating the image. Inspired by FileController::updateFileAction().
     *
     * @param SellerImage $file   Seller Image ID.
     * @param string $eventName  the event type.
     *
     * @return AmpSellerImage
     */
    protected function updateImageFile(AmpSellerImage $file) {
        $fileUpdateForm = $this->createForm($file->getUpdateFormId());
        try {
            if (null === $file) {
                throw new \InvalidArgumentException(sprintf('%d image id does not exist', $file->getId()));
            }

            $event = new FileCreateOrUpdateEvent(null);

            $event->setModel($file);
            $event->setOldModel($file);

            $fileForm = $this->getRequest()->files->get($fileUpdateForm->getName());

            if (isset($fileForm['file'])) {
                $event->setUploadedFile($fileForm['file']);
            }else{// Hack ARTABAN GL ( Evite message d'erreur lorsque l'on sauvegarde le texte sans avoir changé d'image )
                return null;
            }

            $this->dispatch(TheliaEvents::IMAGE_SAVE, $event);

            $fileUpdated = $event->getModel();

            $this->adminLogAppend(
                    AdminResources::MODULE, AccessManager::UPDATE, sprintf('Image with Ref %s (ID %d) modified', $fileUpdated->getTitle(), $fileUpdated->getId())
            );

            if ($this->getRequest()->get('save_mode') == 'close') {
                return $this->generateRedirect(
                                URL::getInstance()->absoluteUrl($file->getRedirectionUrl(), ['current_tab' => 'images'])
                );
            } else {
                return $this->generateSuccessRedirect($fileUpdateForm);
            }
        } catch (PropelException $e) {
            $message = $e->getMessage();
        } catch (\Exception $e) {
            $message = sprintf('Sorry, an error occurred: %s', $e->getMessage() . ' ' . $e->getFile());
        }

        if (isset($message)) {
            Tlog::getInstance()->error(sprintf('Error during image editing : %s.', $message));

            $fileUpdateForm->setErrorMessage($message);

            $this->getParserContext()->addForm($fileUpdateForm)->setGeneralError($message);
        }

        return $file;
    }

    public function deleteImageAction($imageId) {
        // Check current user authorization
//        if (null !== $response = $this->checkAuth($this->resourceCode, $this->getModuleCode(), AccessManager::DELETE)) {
//            return $response;
//        }

        try {
            $seller_image = AmpSellerImageQuery::create()->findPk($imageId);
            $event = new AmpSellerImageEvent($imageId);
            $event->setId($imageId);
            $this->dispatch($this->deleteEventIdentifier, $event);
            $this->performAdditionalDeleteAction($event);
            return $this->generateRedirect($seller_image->getRedirectionUrl());
        } catch (\Exception $e) {
            return $this->renderAfterDeleteError($e);
        }
    }

}
