<?php
// Copyright (c) MetaClass Groningen, 2016

namespace VisualM\ManagementBundle\Form;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

trait TabSetTrait
{
    protected $excludedFromOverige = array('button', 'submit', 'input reset');

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $fieldsets = $form->getConfig()->getAttribute('fieldsets');
        if ($fieldsets !== null) {
            $view->vars['fieldsets'] = $fieldsets;
        }
        $tabs = $form->getConfig()->getAttribute('tabs');
        if ($tabs !== null) {
            $view->vars['tabs'] = $tabs;
        }
    }

    /**
     * @param array $formElements of Form typically $builder->all()
     * @param array $tabs of tab already defined
     * @param string $name for the tab
     * @param null $label for the tab
     * @return Tab active als geen enkele andere tab active is
     */
    protected function getOverigeTab($formElements, $tabs, $name='overige', $label=null, $translationDomain=null)
    {
        $result = new Tab($name, $label, $this->getOverigeFieldNames($formElements, $tabs), null, $translationDomain );
        $result->active = true;
        foreach ($tabs as $tab) {
            if ($tab->active) {
                $result->active = false;
            }
        }
        return $result;
    }

    protected function getOverigeFieldset($formElements, $fieldsets, $name='overige', $label=null)
    {
        return new Fieldset($name, $label, $this->getOverigeFieldNames($formElements, $fieldsets) );
    }

    protected function getOverigeFieldNames($formElements, $fieldsets)
    {
        $result = array();
        forEach($formElements as $child) {
            if (in_array($child->getType()->getName(), $this->excludedFromOverige)) {
                continue;
            }
            $name = (string) $child->getName();
            $found = false;
            reset($fieldsets);
            foreach($fieldsets as $set)
            {
                if ($set->hasFormName($name)) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $result[] = $name;
            }
        }
        return $result;
    }
}