<?php
namespace Backend\BaseBundle\Controller\Backend;

use Backend\BaseBundle\Event\Controller\SetupEvent;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints;
use Backend\BaseBundle\Model;
use Backend\BaseBundle\Event\RoleTypeEvent;
use Backend\BaseBundle\Controller\BaseController;

/**
 * 後台文章管理
 * @Security("has_role_or_superadmin('ROLE_SETUP')")
 * @Route("/setup")
 */
class SetupController extends BaseController
{

    protected function getSetupConfigs()
    {
        $event = new SetupEvent();
        $event->setSite($this->getSite());
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch(SetupEvent::EVENT_SETUP, $event);
        return $event->getConfig();
    }

    protected function updateConfigData($type, $configs)
    {
        $siteConfig = $this->get('backend_base.site_config_builder')->build($this->getSite()->getId());
        $siteConfig->set($type, $configs);
        $operationLog = new Model\OperationLog();
        $operationLog->setSiteId($this->getSite()->getId());
        $operationLog->setSiteUserId($this->getUser()->getId());
        $operationLog->setModifyTable(Model\SiteConfigPeer::TABLE_NAME);
        $operationLog->setModifyColumn(array(
            'type' => $type,
            'configs' => $configs,
        ));
        $operationLog->setModifyType(Model\OperationLogPeer::MODIFY_TYPE_UPDATE);
        $operationLog->save();
    }

    protected function fetchConfigData($type)
    {
        $siteConfig = $this->get('backend_base.site_config_builder')->build($this->getSite()->getId());
        return $siteConfig->get($type);
    }

    /**
     * @Route("/{type}", defaults={"type" = "system"})
     * @Template()
     */
    public function setupAction(Request $request, $type)
    {
        $configs = $this->getSetupConfigs();
        if(!isset($configs[$type])){
            throw $this->createNotFoundException();
        }

        $form = $this->getForm($this->controllerNameGuesser->getShortName(), $configs[$type]['form'], $this->fetchConfigData($type));

        $form->handleRequest($request);

        if ($form->isValid()) {
            try {
                $this->updateConfigData($type, $form->getData());
                $this->addFlash('success', 'message.data.success.save');
            }
            catch(\PropelException $e){
                $this->addFlash('error', 'message.data.error.save');
            }
            return $this->redirectToRouteWithSlug('backend_base_backend_setup_setup', array('type' => $type));
        }

        return array(
            'configs' => $configs,
            'type' => $type,
            'setup_form' => $form->createView(),
        );
    }
}