<?php

namespace KupShop\ContentBundle\Admin;

use KupShop\ContentBundle\Exception\UnknownPageTypeException;
use KupShop\ContentBundle\Util\PageLocator;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Pages extends \Window
{
    protected $template = 'window/pages.tpl';

    protected function getObject()
    {
        return [];
    }

    public function get_vars()
    {
        $vars = parent::get_vars();

        if ($type = getVal('ID')) {
            try {
                if ($this->getAction() == 'delete') {
                    try {
                        $page = $this->getPage($type);
                        $json = $page->getDefaultJson();
                        $this->deleteSQL('pages', ['type' => $type]);
                        $page->createPage();
                    } catch (\Exception $exception) {
                        $this->returnError($exception->getMessage());
                    }
                }
                if (getVal('preview')) {
                    $vars['redirect'] = $this->getPage($type)->getUrl();
                } else {
                    $page = $this->getPage($type);
                    $vars['redirect'] = $page->getUrl();
                }
            } catch (UnknownPageTypeException $e) {
                $errStr = sprintf(translate('errorNotFound', 'base'), $this->translateType(), $this->getID());
                throw new NotFoundHttpException($errStr);
            }
        }

        $vars['preview'] = getVal('preview');

        return $vars;
    }

    public function returnError($ErrStr, $parentRefresh = '', $ID = null)
    {
        redirect('launch.php?s=PagesFragments.php&refresh=close&ErrStr='.urlencode($ErrStr));
    }

    public function handle()
    {
        if ($type = getVal('ID')) {
            // activate page
            if (!$this->selectSQL('pages', ['type' => $type])->fetch()) {
                try {
                    $page = $this->getPage($type);
                    $page->createPage();
                } catch (UnknownPageTypeException $e) {
                }
            }
        }
    }

    private function getPage($type)
    {
        /** @var PageLocator $pageLocator */
        $pageLocator = ServiceContainer::getService(PageLocator::class);

        return $pageLocator->getPageService($type);
    }
}

return Pages::class;
