<?php

/**
 * This is the model class for table "addressbook".
 *
 * The followings are the available columns in table 'addressbook':
 * @property integer $id
 * @property string $title
 * @property integer $type
 */
class AddressbookType
{

    const personal = 1;
    const group = 2;
    const intern = 3;

    public static function getAddressbookType($type)
    {
        $typeAsString = 'undefined';
        switch ($type) {
            case AddressbookType::personal:
                $typeAsString = __('ADDRESSBOOK_MODEL_TYPE_PRIVATE');
                break;
            case AddressbookType::group:
                $typeAsString = __('ADDRESSBOOK_MODEL_TYPE_GROUP');
                break;
            case AddressbookType::intern:
                $typeAsString = __('ADDRESSBOOK_MODEL_TYPE_INTERN');
                break;
        }
        return $typeAsString;
    }
}

class Addressbook extends PhonalisaRecord
{

    public $id;
    public $title;
    public $type;
    public $icon;

    public static function myAttributes()
    {
        return array(
            'id' => 'id',
            'title' => 'title',
            'type' => 'type',
            'icon' => 'icon',
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Addressbook 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 'addressbook';
    }

    // FIXME $sort find nothing if the org_name !is set
    public function getAddresses($userId = '', $limit = 10, $offset = 0, $sort = 'org_name')
    {
        if ($this->type == AddressbookType::personal) {

            // if no user id is given there cant be some search results in personal type
            if ($userId == '') {
                return null;
            }

            $attributes = array('contact_tid' => $this->id, 'contact_owner' => $userId);
            if ($sort == 'name') {
                //FIXME ! are 3  requests needed
                $results = Addresses::model()->find($attributes, 'n_family', $limit, $offset);
                $this->sortResultByName($results);
            } else {
                $results = Addresses::model()->find($attributes, $sort, $limit, $offset);
            }

            return $results;
        }
        $attributes = array('contact_tid' => $this->id);
        $results = Addresses::model()->find($attributes, 'n_family', $limit, $offset);
        if ($sort == 'name') {
            $this->sortResultByName($results);
        }
        return $results;
    }

    public function sortResultByName(&$results)
    {
        $sortedResults = array();
        foreach ($results as $result) {
            if ($result->n_family != '') {
                $sortedResults[strtolower($result->n_family) . '_' . $result->id] = $result;
            } elseif ($result->n_given != '') {
                $sortedResults[strtolower($result->n_given) . '_' . $result->id] = $result;
            }
        }
        ksort($sortedResults);
    }

    /**
     * @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('type, icon, title', 'required'),
            array('type', 'numerical', 'integerOnly' => true),
            array('title, userId , icon', 'safe'),
            array('title', 'length', 'min' => 0, 'max' => 14),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, owner, title, type', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @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(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'title' => __('ADDRESSBOOKS_MODEL_TITLE'),
            'type' => __('ADDRESSBOOKS_MODEL_TYPE'),
            'icon' => __('ADDRESSBOOKS_MODEL_ICON'),
        );
    }

    /**
     * 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($order = 'title')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);

        $filter['pagination'] = array(
            'pageSize' => getGridPageSize('addressbook-grid'),
        );

        if ($filter != null) {
            return new CPhonalisaDataProvider($this, $filter);
        }
    }

    public function getIconPath()
    {
        return Yii::app()->baseUrl . '/img/icons/mainMenu/desktop/sidebar/' . $this->icon;
    }

    public function renderIcon(PhonalisaRecord $data, $row)
    {
        //FIXME do image resize if image is to big for GUI
        if (isset($data->icon)) {
            $imgPath = Yii::app()->baseUrl . '/img/icons/mainMenu/desktop/sidebar/';
            $icon = CHtml::image($imgPath . $data->icon, '', array('style' => 'width:32px; high:32px'));
        } else {
            return false;
        }

        return $icon;
    }

    // VirtualAttribute which holds the addressbook type as string. Use it like : $model->typeName
    public function gettypeName()
    {
        return AddressbookType::getAddressbookType($this->type);
    }

    public function isInternalAddressbook()
    {
        if ($this->type == AddressbookType::intern) {
            return true;
        }
        return false;
    }

    public function renderPermissions(PhonalisaRecord $data, $row, $column)
    {
        $htmlOptions = array('class' => $column->id);
        $permission = null;
        $hiddenValue = '0';

        $parentGroups = $data->getParents(true);
        foreach ($parentGroups as $parent) {
            $permission = Permissions::model()->getPermissionsArray(
                    array(
                        'type' => $column->id,
                        'groupId' => $parent->id,
                        'itemId' => $this->id
                    )
            );

            if ($permission) {
                $htmlOptions['disabled'] = 'disabled';
                $htmlOptions['data-parent'] = 'true';
                $checked = true;
                break;
            }
        }

        if ($permission == null) {
            $permission = Permissions::model()->getPermissionsArray(
                    array(
                        'type' => $column->id,
                        'groupId' => $data->id,
                        'itemId' => $this->id
                    )
            );
            if ($permission) {
                $checked = true;
            } else {
                $checked = false;
            }
        }

        if (!array_key_exists('disabled', $htmlOptions)) {
            $hiddenValue = '0';
        }

        $html = CHtml::hiddenField('Permissions[' . $data->id . '][' . $column->id . ']', $hiddenValue);
        $html.= CHtml::checkBox('Permissions[' . $data->id . '][' . $column->id . ']', $checked, $htmlOptions);

        return $html;
    }

    public function renderTypeName(PhonalisaRecord $data, $row)
    {
        return AddressbookType::getAddressbookType($data->type);
    }

    public function beforeDelete()
    {
        $permissions = Permissions::model()->findAllByAttributes(array('itemId' => $this->id));

        while (count($permissions)) {
            foreach ($permissions as $permission) {
                $permission->delete();
            }
            $permissions = Permissions::model()->findAllByAttributes(array('itemId' => $this->id));
        }
        $permissionModel = new Permissions();
        $permissionModel->createPermissionsFile();


        $addressesFromAddressbook = Addresses::model()->findAllByAttributes(array('contact_tid' => $this->id));
        foreach ($addressesFromAddressbook as $address) {
            $address->delete();
        }
        $addressesFromAddressbook = Addresses::model()->findAllByAttributes(array('contact_tid' => $this->id));
        if (empty($addressesFromAddressbook)) {
            return parent::beforeDelete();
        } else {
            $this->bevoreDelete();
        }
    }

    public function afterDelete()
    {
        return parent::afterDelete();
    }

    public function getAddressesNumber()
    {
        $attribures = array('contact_tid' => $this->id);

        if ($this->type == AddressbookType::personal) {
            $attribures['contact_owner'] = app()->user->realUserInstance->id;
        }

        return Addresses::model()->countByAttributes($attribures);
    }

    public function allAddressBooksProvider()
    {
        return new CArrayDataProvider($this->findAll(), array('pagination' => false));
    }

    public function humanReadableSearchFilterForType()
    {
        $list = array(
            AddressbookType::personal => AddressbookType::getAddressbookType(AddressbookType::personal),
            AddressbookType::group => AddressbookType::getAddressbookType(AddressbookType::group),
            AddressbookType::intern => AddressbookType::getAddressbookType(AddressbookType::intern)
        );
        asort($list);
        return $list;
    }
}
