<?php

namespace Icinga\Module\Director\Forms;

use Icinga\Module\Director\Data\Db\DbObject;
use Icinga\Module\Director\DirectorObject\Automation\Basket;
use Icinga\Module\Director\Web\Form\DirectorObjectForm;
use Zend_Form_SubForm as ZfSubForm;

class BasketForm extends DirectorObjectForm
{
    protected $listUrl = 'director/baskets';

    protected function getAvailableTypes()
    {
        return [
            'Command'            => $this->translate('Command Definitions'),
            'ExternalCommand'    => $this->translate('External Command Definitions'),
            'CommandTemplate'    => $this->translate('Command Template'),
            'HostGroup'          => $this->translate('Host Group'),
            'IcingaTemplateChoiceHost' => $this->translate('Host Template Choice'),
            'HostTemplate'       => $this->translate('Host Templates'),
            'ServiceGroup'       => $this->translate('Service Groups'),
            'IcingaTemplateChoiceService' => $this->translate('Service Template Choice'),
            'ServiceTemplate'    => $this->translate('Service Templates'),
            'ServiceSet'         => $this->translate('Service Sets'),
            'UserGroup'          => $this->translate('User Groups'),
            'UserTemplate'       => $this->translate('User Templates'),
            'User'               => $this->translate('Users'),
            'NotificationTemplate' => $this->translate('Notification Templates'),
            'Notification'       => $this->translate('Notifications'),
            'TimePeriod'         => $this->translate('Time Periods'),
            'Dependency'         => $this->translate('Dependencies'),
            'DataList'           => $this->translate('Data Lists'),
            'ImportSource'       => $this->translate('Import Sources'),
            'SyncRule'           => $this->translate('Sync Rules'),
            'DirectorJob'        => $this->translate('Job Definitions'),
            'Basket'             => $this->translate('Basket Definitions'),
        ];
    }

    /**
     * @throws \Zend_Form_Exception
     */
    public function setup()
    {
        $this->addElement('text', 'basket_name', [
            'label'        => $this->translate('Basket Name'),
            'required'     => true,
        ]);

        $types = $this->getAvailableTypes();

        $options = [
            Basket::SELECTION_NONE   => $this->translate('Ignore'),
            Basket::SELECTION_ALL    => $this->translate('All of them'),
            Basket::SELECTION_CUSTOM => $this->translate('Custom Selection'),
        ];

        $this->addHtmlHint($this->translate(
            'What should we place into this Basket every time we create'
            . ' new snapshot?'
        ));

        $sub = new ZfSubForm();
        $sub->setDecorators([
            ['HtmlTag', ['tag' => 'dl']],
            'FormElements'
        ]);

        foreach ($types as $name => $label) {
            $sub->addElement('select', $name, [
                'label' => $label,
                'multiOptions' => $options,
            ]);
        }

        $this->addSubForm($sub, 'objects');
        $this->addDeleteButton();

        $this->addHtmlHint($this->translate(
            'Choose "All" to always add all of them,'
            . ' "Ignore" to not care about a specific Type at all and'
            . ' opt for "Custom Selection" in case you want to choose'
            . ' just some specific Objects.'
        ));
    }

    protected function setDefaultsFromObject(DbObject $object)
    {
        parent::setDefaultsFromObject($object);
        /** @var Basket $object */
        $values = [];
        foreach ($this->getAvailableTypes() as $type => $label) {
            $values[$type] = Basket::SELECTION_NONE;
        }
        foreach ($object->getChosenObjects() as $type => $selection) {
            if ($selection === true) {
                $values[$type] = Basket::SELECTION_ALL;
            } elseif (is_array($selection)) {
                $values[$type] = Basket::SELECTION_CUSTOM;
            }
        }

        $this->populate([
            'objects' => $values
        ]);
    }

    protected function onRequest()
    {
        parent::onRequest(); // TODO: Change the autogenerated stub
    }

    protected function getObjectClassname()
    {
        return Basket::class;
    }

    public function onSuccess()
    {
        /** @var Basket $basket */
        $basket = $this->object();

        if ($basket->isEmpty()) {
            $this->addError($this->translate("It's not allowed to store an empty basket"));

            return;
        }
        if (! $basket->hasBeenLoadedFromDb()) {
            $basket->set('owner_type', 'user');
            $basket->set('owner_value', $this->getAuth()->getUser()->getUsername());
        }

        parent::onSuccess();
    }

    protected function setObjectSuccessUrl()
    {
        /** @var Basket $basket */
        $basket = $this->object();
        $this->setSuccessUrl(
            'director/basket',
            ['name' => $basket->get('basket_name')]
        );
    }
}
