<?php

/**
 * This is the model class for table "node".
 *
 * The followings are the available columns in table 'node':
 * @property integer $id
 * @property integer $node_id
 * @property string $link
 * @property string $data_type
 * @property integer $data_id
 * @property integer $rank
 * @property string $hidden
 * @property string $code
 *
 * The followings are the available model relations:
 * @property Node $node
 * @property Node[] $nodes
 * @property NodeI18n[] $i18ns
 * @property NodeI18n $i18n
 */
class Node extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Node the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'node';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('node_id, data_id, rank', 'numerical', 'integerOnly' => true),
            array('link', 'length', 'max' => 128),
            array('data_type', 'length', 'max' => 64),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, node_id, link, data_type, data_id, menu_tag, rank', 'safe', 'on' => 'search'),
            array('hidden, code', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
            'nodes' => array(self::HAS_MANY, 'Node', 'node_id', 'order' => 'rank asc'),
            'i18ns' => array(self::HAS_MANY, 'NodeI18n', 'id', 'index' => 'lang'),
            'i18n' => array(self::HAS_ONE, 'NodeI18n', 'id', 'condition' => 'lang=\'' . Yii::app()->language . '\''),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'node_id' => 'Родитель',
            'link' => 'Псевдоним в адресной строке',
            'data_type' => 'Тип',
            'data_id' => 'Идентификатор экземпляра типа страницы',
            'hidden' => 'Страница скрыта',
            'rank' => 'Вес в списке',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

//        $criteria->compare('id', $this->id);
        $criteria->compare('node_id', $this->node_id);
        $criteria->compare('link', $this->link, true);
        $criteria->compare('data_type', $this->data_type, true);
        $criteria->compare('data_id', $this->data_id);
        $criteria->compare('menu_tag', $this->menu_tag, true);
        $criteria->compare('rank', $this->rank);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function getPathIds()
    {
        $res = array();
        $c = $this;
        while ($c) {
            $res[] = $c->id;
            $c = $c->node;
        }
        return array_reverse($res);
    }

    public function getPath()
    {
        $res = array();
        $c = $this;
        while ($c) {
            $res[] = $c;
            $c = $c->node;
        }
        return array_reverse($res);
    }

    public $nodeTypes = array();

    public function delete()
    {
        foreach ($this->nodes as $node)
            $node->delete();
        NodeTypeHelper::getNodeType($this->data_type)->deleteData($this->id);
        return parent::delete();
    }

    public function save($runValidation = true, $attributes = null)
    {
        $r = parent::save($runValidation, $attributes);
        if (empty($this->link)) {
            $this->link = $this->id;
            $this->saveAttributes($this->attributes);
        }
        return $r;
    }

    private static $_idByDataIdCache = array();

    public static function idByDataId($data_type, $data_id = null)
    {
        if (isset(self::$_idByDataIdCache["$data_type@@$data_id"])) return self::$_idByDataIdCache["$data_type@@$data_id"];
        if (isset($data_id))
            $node = self::model()->find("data_id=:data_id  and data_type = :data_type", array(
                ':data_id' => $data_id,
                ':data_type' => $data_type
            ));
        else
            $node = self::model()->find("data_type = :data_type", array(
                ':data_type' => $data_type
            ));
        self::$_idByDataIdCache["$data_type@@$data_id"] = $node->id;
        return $node->id;
    }


}