<?php
    /*********************************************************************************
     * Zurmo is a customer relationship management program developed by
     * Zurmo, Inc. Copyright (C) 2017 Zurmo Inc.
     *
     * Zurmo is free software; you can redistribute it and/or modify it under
     * the terms of the GNU Affero General Public License version 3 as published by the
     * Free Software Foundation with the addition of the following permission added
     * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
     * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
     * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
     *
     * Zurmo is distributed in the hope that it will be useful, but WITHOUT
     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
     * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
     * details.
     *
     * You should have received a copy of the GNU Affero General Public License along with
     * this program; if not, see http://www.gnu.org/licenses or write to the Free
     * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
     * 02110-1301 USA.
     *
     * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
     * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
     *
     * The interactive user interfaces in original and modified versions
     * of this program must display Appropriate Legal Notices, as required under
     * Section 5 of the GNU Affero General Public License version 3.
     *
     * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
     * these Appropriate Legal Notices must retain the display of the Zurmo
     * logo and Zurmo copyright notice. If the display of the logo is not reasonably
     * feasible for technical reasons, the Appropriate Legal Notices must display the words
     * "Copyright Zurmo Inc. 2017. All rights reserved".
     ********************************************************************************/

    /**
     * Element to render a collection of dropdown elements that are connected together. This element renders a
     * dropDown dependency derived attribute.
     */
    class DropDownDependencyElement extends Element
    {
        /**
         * Instance of metadata associated with the specified attribute
         * @var DropDownDependencyDerivedAttributeMetadata
         */
        protected $dropDownDependencyDerivedAttributeMetadata;

        protected function makeMetadata()
        {
            assert('$this->attribute != null');
            assert('$this->model instanceof RedBeanModel');
            $this->dropDownDependencyDerivedAttributeMetadata = DropDownDependencyDerivedAttributeMetadata::
                                                                getByNameAndModelClassName($this->attribute,
                                                                                           get_class($this->model));
        }

        /**
         * (non-PHPdoc)
         * @see Element::renderNonEditable()
         */
        protected function renderEditable()
        {
            $this->makeMetadata();
            return parent::renderEditable();
        }

        /**
         * (non-PHPdoc)
         * @see Element::renderControlEditable()
         */
        protected function renderControlEditable()
        {
            $unserializedMetadata  = unserialize($this->dropDownDependencyDerivedAttributeMetadata->serializedMetadata);
            $onChangeScript        = null;
            $dependencyData        = array();
            $attributes            = $this->dropDownDependencyDerivedAttributeMetadata->getUsedAttributeNames();
            $content               = "<table> \n";
            $parentInputId         = null;
            $parentAttributeLabel  = null;
            foreach ($attributes as $position => $attribute)
            {
                $element                    = new DropDownElement($this->model,
                                                                  $attribute,
                                                                  $this->form,
                                                                  array('addBlank' => true));

                $element->editableTemplate  = $this->getEditableTemplate();
                $content                   .= $element->render();
                $inputId                    = $element->getIdForSelectInput();
                $onChangeScript .= "$('#" . $inputId . "').bind('change', function()
                {
                    " . $this->getDependencyManagerResolveScriptCall() . "
                }
                );";
                $dependencyData[]         = $this->resolveDependencyData($inputId,
                                                                         $parentInputId,
                                                                         $unserializedMetadata['mappingData'],
                                                                         $position,
                                                                         null,
                                                                         $parentAttributeLabel);
                $parentInputId            = $inputId;
                $parentAttributeLabel     = $this->model->getAttributeLabel($attribute);
            }
            $content   .= "</table> \n";
            $this->resolveScriptContent($onChangeScript, $dependencyData);
            return $content;
        }

        protected static function resolveDependencyData($inputId, $parentInputId, $mappingData, $position,
                                                        $existingValue, $parentAttributeLabel)
        {
            assert('is_string($inputId)');
            assert('$parentInputId == null || is_string($parentInputId)');
            assert('is_array($mappingData)');
            assert('is_int($position)');
            assert('$existingValue == null || is_string($existingValue)');
            assert('is_string($parentAttributeLabel) || $parentAttributeLabel == null');
            $dependencyData = array();
            $dependencyData['inputId']              = $inputId;
            $dependencyData['parentInputId']        = $parentInputId;
            $dependencyData['valueToAlwaysShow']    = $existingValue;
            if ($parentAttributeLabel != null)
            {
                $dependencyData['notReadyToSelectText'] = ZurmoHtml::encode(Zurmo::t('Core', 'First select the {attributeLabel}',
                                                                 array('{attributeLabel}' => $parentAttributeLabel)));
            }
            else
            {
                $dependencyData['notReadyToSelectText'] = null;
            }
            if (isset($mappingData[$position]['valuesToParentValues']))
            {
                $dependencyData['valuesToParentValues'] = $mappingData[$position]['valuesToParentValues'];
            }
            else
            {
                $dependencyData['valuesToParentValues'] = null;
            }
            return $dependencyData;
        }

        protected function resolveScriptContent($onChangeScript, $dependencyData)
        {
            assert('is_string($onChangeScript)');
            assert('is_array($dependencyData)');
            Yii::app()->clientScript->registerScriptFile(
                Yii::app()->getAssetManager()->publish(
                    Yii::getPathOfAlias('application.core.elements.assets')
                    ) . '/DropDownDependencyManager.js',
                CClientScript::POS_END
            );
            $managerObjectName = $this->getDependencyManagerScriptObjectName();
            $suffix            = $this->getDependencyManagerScriptSuffix();
            $script = "
                var " . $managerObjectName . " = new DropDownDependencyManager('" . CJSON::encode($dependencyData) . "');
                " . $this->getDependencyManagerResolveScriptCall() . ";";
            Yii::app()->clientScript->registerScript(
                'dropDownDependencyManager' . $suffix,
                $script,
                CClientScript::POS_END
            );
            Yii::app()->clientScript->registerScript(
                'dropDownDependencyOnChange' . $suffix,
                $onChangeScript,
                CClientScript::POS_END
            );
        }

        protected function getDependencyManagerScriptObjectName()
        {
            return 'DependencyManager' . $this->getDependencyManagerScriptSuffix();
        }

        protected function getDependencyManagerScriptSuffix()
        {
            return $this->dropDownDependencyDerivedAttributeMetadata->name;
        }

        protected function getDependencyManagerResolveScriptCall()
        {
            return $this->getDependencyManagerScriptObjectName() . ".resolveOptions()";
        }

        /**
         * (non-PHPdoc)
         * @see Element::renderNonEditable()
         */
        protected function renderNonEditable()
        {
            $this->makeMetadata();
            return parent::renderNonEditable();
        }

        /**
         * (non-PHPdoc)
         * @see Element::renderControlNonEditable()
         */
        protected function renderControlNonEditable()
        {
            $attributes = $this->dropDownDependencyDerivedAttributeMetadata->getUsedAttributeNames();
            $content    = null;
            foreach ($attributes as $attribute)
            {
                $element                        = new DropDownElement($this->model,
                                                                  $attribute,
                                                                  $this->form);
                $element->nonEditableTemplate   = $this->getNonEditableTemplate();
                if ($content != null)
                {
                    $content .= ' &rarr; ';
                }
                $content                       .= $element->render();
            }
            return $content;
        }

        /**
         * (non-PHPdoc)
         * @see Element::renderLabel()
         */
        protected function renderLabel()
        {
            $content = $this->dropDownDependencyDerivedAttributeMetadata->getLabelByLanguage(Yii::app()->language);
            if ($this->form === null)
            {
                return Yii::app()->format->text($content);
            }
            return ZurmoHtml::tag('label', array(), $content);
        }

        /**
         * (non-PHPdoc)
         * @see Element::renderError()
         */
        protected function renderError()
        {
            return null;
        }

        protected function getEditableTemplate()
        {
            $template  = "<tr><td style='border:0px;' nowrap='nowrap'>\n";
            $template .= "{label}";
            $template .= "</td><td width='100%' style='border:0px;'>\n";
            $template .= '&#160;{content}{error}';
            $template .= "</td></tr>\n";
            return $template;
        }

        protected function getNonEditableTemplate()
        {
            return "{content}";
        }
    }
?>