<?php

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

include_once './includes/users/Member.inc.php';

include_once './includes/utils/MapperUtils.inc.php';

/**
 * This class allows for an easy listing of users.
 *
 * @author Thomas Schwery <thomas.schwery@epfl.ch>
 */
class MemberLister {


    public static function getAll() {
        $users = MemberLister::getMembers("");
        return $users;
    }

    /**
     * Returns all registred users.
     * 
     * @return array(Member)
     */
    public static function getAllMembers() {
        $users = MemberLister::getMembers("");

        $members = array_filter($users, "selectMembers");

        return $members;
    }

    /**
     * Returns the user corresponding to the given username.
     * 
     * @param string $username
     * @return Member/bool
     */
    public static function getByLogin($username) {
        $members = MemberLister::getmembers("WHERE username = '$username'");

        if (array_key_exists("0", $members) AND ($members[0] instanceof Member)) {
            return $members[0];
        } else {
            return false;
        }
    }

    public static function getByBirthday($windowStart, $windowEnd) {
        $start = date("md", $windowStart);
        $end = date("md", $windowEnd);
        $restriction = "WHERE DATE_FORMAT(`birthday`, '%m%d') BETWEEN '$start' AND '$end'";
        $users = MemberLister::getmembers($restriction);
        $members = array_filter($users, "selectMembers");
        return $members;
    }

    /**
     * Returns the users corresponding to the given restriction.
     *
     * @param string $restriction A SQL syntax restriction
     * @return array(Member)
     */
    private static function getMembers($restriction) {
        $sql = "SELECT identifier FROM users $restriction;";
        $result = MySQLDatabase::getInstance()->runRequest($sql);

        if ($result) {
            $result1 = array_map("mapIdentifierToMember", $result);
            return $result1;
        } else {
            return array();
        }
    }
}
?>