<?php
class BattlesLocations extends CActiveRecord {

    public function tableName() {
        return 'battles_locations';
    }

    public function rules() {
        return array(
            array('id_location, name_location, level_min, level_max, type_location, side_default, health_default, participation_default, side_now, health_now, participation_now', 'required'),
            array('type_location, side_default, side_now', 'numerical', 'integerOnly' => true),
            array('id_location, level_min, level_max, health_default, participation_default, health_now, participation_now', 'length', 'max' => 11),
            array('name_location', 'length', 'max' => 256),
            array('status', 'safe'),
            array('id_location, name_location, level_min, level_max, type_location, side_default, health_default, participation_default, side_now, health_now, participation_now', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
            'childNavigator' => array(self::HAS_MANY, 'BattlesNavigator', 'child_location'),
            'idNavigator' => array(self::HAS_MANY, 'BattlesNavigator', 'id_location'),
            'usersForBots' => array(self::HAS_MANY, 'Users', 'battle_id',
                            'with'=>'idRole',
                            'condition'=>'idRole.id_cat_role != 5 AND usersForBots.health_now > 0 AND usersForBots.battle_time_in < '.(time()-10).''),
            'users' => array(self::HAS_MANY, 'Users', 'battle_id',
                            'with'=>'idRole',
                            'condition'=>'idRole.id_cat_role != 5'),
            'bots' => array(self::HAS_MANY, 'Users', 'battle_id',
                            'with'=>'idRole',
                            'condition'=>'idRole.id_cat_role = 5'),
        );
    }

    public function attributeLabels() {
        return array(
            'id_location' => '#',
            'name_location' => 'Название',
            'level_min' => 'Уровен',
            'level_max' => 'Level Max',
            'type_location' => 'Type Location',
            'side_default' => 'Side Default',
            'health_default' => 'Health Default',
            'participation_default' => 'Participation Default',
            'side_now' => 'Side Now',
            'health_now' => 'Health Now',
            'participation_now' => 'Participation Now',
        );
    }

    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id_location', $this->id_location, true);
        $criteria->compare('name_location', $this->name_location, true);
        $criteria->compare('level_min', $this->level_min, true);
        $criteria->compare('level_max', $this->level_max, true);
        $criteria->compare('type_location', $this->type_location);
        $criteria->compare('side_default', $this->side_default);
        $criteria->compare('health_default', $this->health_default, true);
        $criteria->compare('participation_default', $this->participation_default, true);
        $criteria->compare('side_now', $this->side_now);
        $criteria->compare('health_now', $this->health_now, true);
        $criteria->compare('participation_now', $this->participation_now, true);

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

    public function getColumns() {
        $columns = array(
            array(
                'name' => 'id_location',
                'header' => '#',
            ),
            'name_location',
            array(
                'name' => 'level',
                'header' => 'Уровень',
                'value' => function ($data) {
            return $data->level_min . ' - ' . $data->level_max;
        },
            ),
            array(
                'name' => 'side_now',
                'header' => 'Контроль',
                'value' => function ($data) {
            if ($data->side_now == 1)
                return 'Краллы';
            elseif ($data->side_now == 2)
                return 'Элийцы';
            else
                return 'Нейтральная';
        },
            ),
            array(
                'name' => 'users',
                'header' => 'Кол-во игроков',
                'value' => 'Users::getUsersInLocation($data->id_location)',
            ),
            array(
                'name' => 'bots',
                'header' => 'Кол-во ботов',
                'value' => 'Users::getBotsInLocation($data->id_location)',
            ),
            array(
                'class' => 'CButtonColumn',
                'template' => '{control}', //include the standard buttons plus the new status button
                'buttons' => array(
                    'control' => array(
                        'url' => 'array("battles/update", "id"=>$data->id_location)',
                        'label' => '<span class="glyphicon glyphicon-cog"></span>',
                        'options' => array('title'=>'Управление ботами', 'style'=>'color: #000000;'),
                    )
                )
            )
        );

//        $columns = array(
//            'login',
//            array(
//                'name' => 'password',
//                'htmlOptions' => array('class' => 'password'),
//                'filterHtmlOptions' => array('class' => 'password'),
//                'headerHtmlOptions' => array('class' => 'password'),
//            ),
//            array(
//                'name' => 'id_role',
//                'type' => 'raw',
//                'value' => 'isset($data->id_role) ? $data->idRole->name_role_ru : ""',
//                'filter' => CHtml::dropDownList('Users[id_role]', $this->id_role, $roles_listdata, array('class' => 'chosen-select', 'empty' => 'Все', 'style' => 'width:100%;', 'data-placeholder' => ' ')),
//                'htmlOptions' => array('class' => 'role'),
//                'filterHtmlOptions' => array('class' => 'role'),
//                'headerHtmlOptions' => array('class' => 'role'),
//            ),
//            array(
//                'name' => 'email',
//                'htmlOptions' => array('class' => 'email'),
//                'filterHtmlOptions' => array('class' => 'email'),
//                'headerHtmlOptions' => array('class' => 'email'),
//            ),
//            array(
//                'name' => 'created',
//                'filter' => Yii::App()->controller->widget('zii.widgets.jui.CJuiDatePicker', array(
//                    'model' => $model,
//                    'attribute' => 'created',
//                    'language' => 'ru',
//                    'htmlOptions' => array(
//                        'id' => 'datepicker-created',
//                        'size' => '10',
//                    ),
//                    'defaultOptions' => array(// (#3)
//                        'showOn' => 'focus',
//                        'dateFormat' => 'd.m.Y',
//                        'showOtherMonths' => true,
//                        'selectOtherMonths' => true,
//                        'changeMonth' => true,
//                        'changeYear' => true,
//                        'showButtonPanel' => true,
//                    )
//                        ), true),
//                'htmlOptions' => array('class' => 'created'),
//                'filterHtmlOptions' => array('class' => 'created'),
//                'headerHtmlOptions' => array('class' => 'created'),
//            ),
//            array(
//                'name' => 'last_visit',
//                'filter' => Yii::App()->controller->widget('zii.widgets.jui.CJuiDatePicker', array(
//                    'model' => $model,
//                    'attribute' => 'last_visit',
//                    'language' => 'ru',
//                    'htmlOptions' => array(
//                        'id' => 'datepicker-last-visit',
//                        'size' => '10',
//                    ),
//                    'defaultOptions' => array(// (#3)
//                        'showOn' => 'focus',
//                        'dateFormat' => 'd.m.Y',
//                        'showOtherMonths' => true,
//                        'selectOtherMonths' => true,
//                        'changeMonth' => true,
//                        'changeYear' => true,
//                        'showButtonPanel' => true,
//                    )
//                        ), true),
//                'htmlOptions' => array('class' => 'last_visit'),
//                'filterHtmlOptions' => array('class' => 'last_visit'),
//                'headerHtmlOptions' => array('class' => 'last_visit'),
//            )
//        );
        return $columns;
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return BattlesLocations the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * Возвращает название локации и ее сторону
     * @param int $id ид локации
     * @param boolean $arrow использовать указатель
     * @return string 
     */
    public static function getNameWithIcon($id_location, $arrow = false) {
        $location = self::model()->findByPk($id_location);
        $icon = 'side_' . $location->side_now;
        if ($arrow) {
            $icon .= '_' . $arrow;
        }
        return '<img src="/images/icons/battles/' . $icon . '.png" alt="*" /> ' . $location->name_location;
    }

    /**
     * Подсчитывает доминацию в зависимости от стороны
     * @param type $side сторона
     * @return int
     */
    public static function getDomination($side, $level = null) {
        $criteria = new CDbCriteria();
        if ($level > 0) {
            if ($level <= 18) {
                $criteria->addCondition('level_max <= 18');
            }
            else {
                $criteria->addCondition('level_max > 18');
            }
        }
        $all = self::model()->count();
        $criteria->compare('side_now', $side);
        $criteria->compare('status', 1);
        $count = self::model()->count($criteria);
        
        $result = round($count * 100 / $all);
        if ($result > 70)
            $result = 70;
        elseif ($result < 30)
            $result = 30;

        return $result;
    }

    /**
     * Выводит иконки в зависимости от доминации
     * @param type $side
     * @return int
     */
    public static function getDominationIcon($side) {
        $percent = self::getDomination($side);
        if ($percent >= 70)
            $result = 3;
        elseif ($percent >= 50)
            $result = 2;
        else
            $result = 1;

        return $result;
    }

}
