<?php

namespace Velis\Bpm\Person;

use Velis\App;
use Velis\Model\DataObject;
use Velis\Model\Cacheable;
use Velis\Model\Routable;
use User\User;

/**
 * Persons group model
 *
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 * @author Olek Procki <olo@velis.pl>
 */
class Group extends DataObject implements Cacheable, Routable
{

    /**
     * List sort options
     */
    const ORDER_NAME          = 'name';
    const ORDER_ID            = 'person_group_id DESC';


    protected static $_listDefaultOrder = self::ORDER_NAME;
    protected static $_filterListParams = true;


    /**
     * Returns related sql table
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.person_group_tab';
    }


    /**
     * Returns view for selecting
     * @return string
     */
    protected function _getListDatasource()
    {
        return 'app.person_group_tab p';
    }


    /**
     * Returns group name
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }


    /**
     *
     * @return User
     */
    public function getUser()
    {
        return User::get($this->owner_user_id);
    }


    /**
     * Checks if a user can access/edit this group
     * @return boolean
     */
    public function checkAccess()
    {
        if ($this->is_public) {
            return true;
        }

        if ($this->owner_user_id == App::$user->id()) {
            return true;
        }

        if (App::$user->hasPriv('Company', 'PersonGroupEditAll')) {
            return true;
        }

        return false;
    }


    /**
     * Returns group list
     *
     * @param int $page
     * @param array|ArrayObject $params
     * @param string $order
     * @param int $limit
     * @param string|array $fields
     *
     * @return \Velis\Bpm\Person\Group[]
     */
    public static function getList($page = 1, $params = null, $order = self::ORDER_NAME, $limit = self::ITEMS_PER_PAGE, $fields = null)
    {

        if ($params['owner_user_id']) {
            self::$_listConditions[] = '(owner_user_id = :owner_user_id OR is_public = 1)';
            self::$_listParams['owner_user_id'] = $params['owner_user_id'];
            unset($params['owner_user_id']);
        }


        return parent::getList($page, $params, $order, $limit, $fields);
    }


    /**
     * Retruns rewrite route name
     * @return string
     */
    public function getRouteName()
    {
        return 'person-group';
    }


    /**
     * Returns info page url
     * @return string
     */
    public function getStandardUrl()
    {
        return '/company/person-group?person_group_id=' . $this->id();
    }


    /**
     * add person to group
     *
     * @param \Velis\Bpm\Person|int $person
     * @return \Velis\Bpm\Person\Group
     */
    public function addPerson($person)
    {
        self::$_db->insert(
            'app.person_group_person_tab',
            array(
                'person_id' => $person instanceof Person ? $person->id() : $person,
                'person_group_id' => $this->id()
            )
        );
        return $this;
    }


    /**
     * remove person from group
     *
     * @param \Velis\Bpm\Person|int $personId
     * @return void
     */
    public function removePerson($person)
    {
        self::$_db->execDML(
            'DELETE FROM app.person_group_person_tab
             WHERE person_group_id = :person_group_id
               AND person_id = :person_id',
            array(
                'person_id' => $person instanceof Person ? $person->id() : $person,
                'person_group_id' => $this->id()
            )
        );
    }


    /**
     * remove persons group
     *
     * @return void
     */
    public function remove()
    {
        self::$_db->startTrans();

        try {
            self::$_db->execDML(
                'DELETE FROM app.person_group_person_tab
                 WHERE person_group_id = :person_group_id',
                $this->_getPrimaryKeyParam()
            );

            $this->_remove();
            self::$_db->commit();
        } catch (Exception $e) {
            self::$_db->rollback();
            throw $e;
        }
    }
}
