<?php

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

/**
 * This class represents the rights a user can have on the site.
 *
 * @author Thomas Schwery <thomas.schwery@epfl.ch>
 */
class MemberRight {

    private $identifier;

    private $name;

    private $needsSaving;

    public static function Get($identifier) {
        $sql = "SELECT * FROM `userRight` WHERE `rightId` = $identifier;";

        $result = MySQLDatabase::getInstance()->runRequest($sql);

        $newRight = new MemberRight($identifier);

        $result = $result[0];

        $newRight->setName($result['name']);
        $newRight->needsSaving = false;

        return $newRight;
    }

    public static function Create($name) {
        $name = InputSanitizer::Sanitize($name);

        $sql = "INSERT INTO `userRight` (`rightId`, `name`)
            VALUES (NULL, '$name');";

        $result = MySQLDatabase::getInstance()->runOperation($sql);

        $sql = "SELECT rightId FROM userRight WHERE name = $name LIMIT 1;";
        $result = $database->runRequest($sql);

        $identifier = $result[0]['rightId'];

        $newCategory = MemberRight::Get($identifier);
        return $newCategory;
    }

    public static function Remove($identifier) {
        $sql = "DELETE FROM `userRightEntries` WHERE `rightId` = $identifier;";
        $result = MySQLDatabase::getInstance()->runOperation($sql);

        $sql = "DELETE FROM `userRight` WHERE `rightId` = $identifier;";
        $result += MySQLDatabase::getInstance()->runOperation($sql);

        return $result;
    }

    private function __construct($identifier) {
        $this->identifier = $identifier;
    }

    public function  __destruct() {
        if ($this->needsSaving) {
            $this->save();
        }
    }

    private function save() {
        $sql = "UPDATE `userRight` SET
            `name` = '$this->name'
            WHERE `rightId` = $this->identifier;";

        $result = MySQLDatabase::getInstance()->runOperation($sql);
    }

    public function getIdentifier() {
        return $this->identifier;
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
        $this->needsSaving = true;
    }
}
?>
