<?php
namespace common\widgets;
use common\models\Language;
use common\modules\blog\controllers\AjaxController;
use yii\base\InvalidParamException;
use yii\base\Widget;
use yii\bootstrap\ActiveForm;

class Multilanguage extends Widget
{
    public $id;

    public $model_name;

    public $table_name;

    public $langs;

    public $default_lang;

    public $data;

    public $handler = '/blog/ajax/multilang-form';

    public $form;

    public $ajaxView;

    public function init()
    {
        parent::init();
        $this->default_lang = Language::getDefaultLang();
        if(empty($this->langs)) {
            $this->langs = Language::getActiveLanguages();
        }
        if(empty($this->form)) {
            throw new InvalidParamException('Form must be set');
        }
        if(empty($this->ajaxView)) {
            throw new InvalidParamException('Ajaxview must be set');
        }
        if(empty($this->data) || !is_array($this->data)) {
            throw new InvalidParamException('Data must be set and be array');
        } else {
            $first = 1;
            foreach ($this->data as $lang => $item) {
                if ($first) {
                    $this->model_name = $item->className();
                    $this->table_name = $item->tableName();
                    $first = 0;
                } else {
                    if($item->className() !== $this->model_name || $item->tableName() !== $this->table_name) {
                        throw new InvalidParamException('Every data element must have the same class and table');
                    }
                }
            }
        }
    }

    public function run()
    {
        echo $this->render('multilanguage-begin', [
            'id' => $this->id,
            'model_name' => $this->model_name,
            'table_name' => $this->table_name,
            'data' => $this->data,
            'langs' => $this->langs,
            'handler' => $this->handler,
            'default_lang' => $this->default_lang,
            'ajaxView' => $this->ajaxView,
        ]);
        foreach($this->data as $lang => $item) {
            $item->language_id = $lang;
            echo $this->render($this->ajaxView, ['model' => $item, 'form' => $this->form, 'widget_id' => $this->id]);
        }
        echo $this->render('multilanguage-end', [
            'id' => $this->id,
            'model_name' => $this->model_name,
            'table_name' => $this->table_name,
            'data' => $this->data,
            'langs' => $this->langs,
            'handler' => $this->handler,
            'default_lang' => $this->default_lang,
            'ajaxView' => $this->ajaxView,
        ]);
    }
}