<?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'),
            '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'),
            '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 = [
            'IGNORE' => $this->translate('Ignore'),
            'ALL'    => $this->translate('All of them'),
            '[]'     => $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] = 'IGNORE';
        }
        foreach ($object->getChosenObjects() as $type => $selection) {
            if ($selection === true) {
                $values[$type] = 'ALL';
            } elseif (is_array($selection)) {
                $values[$type] = '[]';
            }
        }

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

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

    protected function getObjectClassname()
    {
        return '\\Icinga\\Module\\Director\\DirectorObject\\Automation\\Basket';
    }

    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')]
        );
    }
}
