<?php
/**
 * Created by Error202
 * Date: 24.08.2018
 */

namespace core\components;


use yii\base\DynamicModel;
use Yii;

class LanguageDynamicModel extends DynamicModel
{
	private $new_labels = [];
	private $new_hints = [];
	private $new_rules = [];

	public function __construct( array $attributes = [], array $config = [] )
	{
		parent::__construct( array_merge($this->getPublicAttributes(), $this->prepareLanguageAttributes()), $config );
	}

	private function prepareLanguageAttributes()
	{
		$language_attributes = [];
		$labels = $this->attributeLabels();
		$hints = $this->attributeHints();
		foreach ($this->rules() as $rule) {
			$attributes = is_array($rule[0]) ? $rule[0] : [$rule[0]];
			$type = $rule[1];
			if ($type == 'string') {
				foreach (Yii::$app->params['translatedLanguages'] as $language => $language_name) {
					$rule_attributes = [];
					foreach ($attributes as $attribute) {
						// add attribute
						$language_attributes[] = $attribute . '_' . $language;
						$this->new_labels[$attribute . '_' . $language] = isset($labels[$attribute]) ? $labels[$attribute] : null;
						$this->new_hints[$attribute . '_' . $language] = isset($hints[$attribute]) ? $hints[$attribute] : null;
						$rule_attributes[] = $attribute . '_' . $language;
					}
					// add rule
					if (!empty($rule_attributes)) {
						$this->new_rules[] = [ $rule_attributes, $rule[1] ];
					}
				}
			}
		}
		return $language_attributes;
	}

	public function attributeLabels(){
		return $this->new_labels;
	}

	public function rules() {
		return $this->new_rules;
	}

	public function getPublicAttributes () {
		return call_user_func('get_object_vars', $this);
	}

}