<?php

include_once './includes/users/userRights/MemberRight.inc.php';

include_once './includes/database/MySQLDatabase.inc.php';

/**
 * This class is responsible for the operations on MemberRight arrays.
 *
 * For example, the saving of a user's rights.
 *
 * @author Thomas Schwery <thomas.schwery@epfl.ch>
 */
class MemberRightArray {
    
    public static function save(array $rights, Member $user) {

        $userId = $user->getIdentifier();


        $sql = "DELETE FROM `userRightEntries` WHERE `userId` = $userId";
        $result = MySQLDatabase::getInstance()->runOperation($sql);

        $sql = "INSERT INTO `userRightEntries` (`rightId`, `userId`) VALUES";

        foreach($rights as $key => $right) {
            $rightId = $right->getIdentifier();

            $sql .= "($rightId, $userId)";

            if (key_exists($key+1, $rights)) {
                $sql .= ", ";
            }
        }
        if (count($rights) > 0) {
            $result = MySQLDatabase::getInstance()->runOperation($sql);
        }
    }

    public static function hasRight(Member $user, MemberRight $right) {
        $userRights = $user->getRights();

        foreach($userRights as $userRight) {
            if ($right->getName() == $userRight->getName()) return true;
        }

        return false;
    }

    public static function hasRightNamed(Member $user, $rightName) {
        $userRights = $user->getRights();

        foreach($userRights as $right) {
            if ($right->getName() == $rightName) return true;
        }

        return false;
    }
}
?>
