<?php
    
    namespace common\modules\language\widgets;
    
    use common\modules\language\models\Language;
    use yii\base\InvalidConfigException;
    use yii\bootstrap\Widget;
    use yii\db\ActiveRecord;
    use yii\widgets\ActiveForm;
    
    class LanguageForm extends Widget
    {
        
        /**
         * @var ActiveRecord[] $model_langs
         */
        public $model_langs = [];
        
        /**
         * @var string $formView
         */
        public $formView;
        
        /**
         * @var string $id_prefix
         */
        public $id_prefix = 'lang';
        
        /**
         * @var ActiveForm $form
         */
        private $_form;
        
        /**
         * @var Language[] $languages
         */
        private $languages = [];
        
        public function init()
        {
            parent::init();
            if($this->formView === NULL) {
                throw new InvalidConfigException('Form view must be set');
            }
            if(empty( $this->model_langs ) || !is_array($this->model_langs)) {
                throw new InvalidConfigException('Language models must be passed');
            }
            if(empty( $this->getForm() )) {
                throw new InvalidConfigException('Form model must be set');
            }
            $this->languages = Language::find()
                                       ->where([ 'status' => true ])
                                       ->orderBy([ 'default' => SORT_DESC ])
                                       ->indexBy('language_id')
                                       ->all();
        }
        
        public function run()
        {
            return $this->render('language_form_frame', [
                'languages'   => $this->languages,
                'form_view'   => $this->formView,
                'model_langs' => $this->model_langs,
                'form'        => $this->getForm(),
                'id_prefix'   => $this->id_prefix,
            ]);
        }
        
        public function getForm(): ActiveForm
        {
            return $this->_form;
        }
        
        public function setForm(ActiveForm $value)
        {
            $this->_form = $value;
        }
    }