<?php

abstract class EditAction extends NodeAction
{
    public $modelName;
    public $i18nModelName;
    public $viewAlias;


    public function run()
    {
        $this->init();

        /** @var $model Node */
        $modelName = $this->modelName;
        $i18nModelName = $this->i18nModelName;
        /** @var $typeModel CActiveRecord */
        $model = null;
        if (isset($this->node->data_id))
            $model = call_user_func_array(array(&$modelName, 'model'), array())->findByPk($this->node->data_id);

        if ($model === null) $model = new $modelName();

        $i18nModels = array();
        if ($i18nModelName !== null) {
            foreach (Yii::app()->params['languages'] as $lang) {
                if (!isset($model->i18ns[$lang])) {
                    $i18nModel = new $i18nModelName();
                    $i18nModel->id = $model->id;
                    $i18nModel->lang = $lang;
                    $i18nModels[$lang] = $i18nModel;
                } else {
                    $i18nModels[$lang] = $model->i18ns[$lang];
                }
            }
        }
        if (isset($_POST[$modelName]) || (($i18nModelName !== null) && isset($_POST[$i18nModelName]))) {

            if (isset($_POST[$modelName])) $model->attributes = $_POST[$modelName];

            $i18nValidation = $model->validate();

            if (($i18nModelName !== null) && isset($_POST[$i18nModelName])) {
                foreach ($_POST[$i18nModelName] as $lang => $post) {
                    $i18nModels[$lang]->attributes = $post;
                    $i18nValidation = $i18nModels[$lang]->validate() && $i18nValidation;
                }
            }
            if ($i18nValidation) {
                if ($i18nModelName !== null) {
                    $model->i18ns = $i18nModels;
                }
                $model->save(false);
                if ($i18nModelName !== null) {
                    foreach ($i18nModels as $i18nModel) {
                        if (empty($i18nModel->id)) $i18nModel->id = $model->id;
                        $i18nModel->save();
                    }
                }
                if (!isset($this->node->data_id)) {
                    $this->node->data_id = $model->id;
                    $this->node->save();
                }
                $this->controller->refresh();
            }
        }


        $this->controller->render($this->resolveView('_form'), array(
            'model' => $model,
            'i18nModels' => $i18nModels,
        ));
    }
}
