<?php
class Discussion{
	
	protected $ID;
	protected $name;
	protected $creator;
	protected $dateCreation;
	protected $accessibility;
	
	protected $valid;
	
	public function __construct($ID){
		$this->ID = $ID;
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE ID=?');
		$req->execute(array($ID));
		if($rep = $req->fetch()){
			$this->valid = TRUE;
			$this->name = $rep['name'];
			$this->creatorID = new Membre($rep['creatorID']);
			$this->dateCreation = $rep['dateCreation'];
			$this->accessibility = $rep['accessibility'];
		}else{
			$this->valid = FALSE;
		}
	}
	
	public function exists(){
		return $this->valid;
	}
	
	public function __toString(){
		$out = 'Discussion\n';
		$out .= '\tID:' . $this->ID . '\n';
		$out .= '\tName:' . $this->name . '\n';
		$out .= '\tCreator:{' . substr(str_replace('\n\t',';',$this->creator->__toString()),0,-1) . '}\n';
		$out .= '\tDate of creation:' . $this->dateCreation . '\n';
		$out .= '\tAccessibility:' . $this->accessibility . '\n';
		return out;
	}
	
	//Getters
	public function getID(){
		return $this->ID;
	}
	
	public function getName(){
		return $this->name;
	}
	
	public function getCreator(){
		return $creator;
	}
	
	public function getDateCreation(){
		return $this->dateCreation;
	}
	
	public function getAccessibility(){
		return $this->accessibility;
	}
	
	
	//Useful Getters
	public function canAccess($membre){
		$out = $this->accessibility === 'p';
		$out = $out or $membre->getID() === $this->creator->getID();
		if(preg_match ( "#^a[0-9]+$#", $this->accessibility ) == 1)
			$out = $out or intval ( substr ( $this->accessibility, 1 ) ) <= $membre->getAdminLevel();
		$out = $out or preg_match ( '#^x([0-9]+;)*' . $membre->getID() . '(;[0-9]+)*$#', $disc ['autorized'] ) == 1;
		$out = $out or $membre->getAdminLevel() >= 14;
		return $out;
	}
	
	
	//Setters
	public function rename($newName){
		if(!exists())
			return NULL;
		if(getFromName($newName))
			return Discussion::NAME_ALREADY_USED;
		if(strlen($newName)>255)
			return Discussion::TOO_LONG_NAME;
		$regex = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.
			'éèàµ_\\-\'()\\[\\]\\\\/,;:.§!ù%£$¤=+\\-*\\#~"|ç@';
		$regex = '#^['.$regex.']+$#';
		if(preg_match($regex,$newName) != 1)
			return Discussion::ILLEGAL_NAME;
		$req->$GLOBALS['bdd']->prepare('UPDATE discussions SET name=? WHERE ID=?');
		$req->execute(array($newName,$this->ID));
		return Discussion::NAME_CHANGED;
	}
	
	public function changeAccessibility($newAccessibility){
		if(!exists())
			return NULL;
		if($newAccessibility !== 'p' and
			preg_match('#x([0-9]+;)*[0-9]+#',$newAccessibility) != 1 and
			preg_match('#a[0-9]+#',$newAccessibility) != 1)
			return Discussion::MALFORMED_ACCESIBILITY;
		$req = $GLOBALS['bdd']->prepare('UPDATE discussions SET accessibility=? WHERE ID=?');
		$req->execute(array($newAccessibility,$this->ID));
		return Discussion::ACCESSIBILITY_CHANGED;
	}
	
	public function setDateCreation($newDateCreation){
		if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $date, $matches) != 1)
			return Discussion::MALFORMED_DATE;
		if (!checkdate($matches[2], $matches[3], $matches[1]))
			return Discussion::MALFORMED_DATE;
		$req = $GLOBALS['bdd']->prepare('UPDATE discussions SET dateCreation=? WHERE ID=?');
		$req->execute(array($newDateCreation,$this->ID));
		return Discussion::DATE_CREATION_CHANGED;
	}
	
	//Discussions getters
	private static function discussionGetterOutput($req){
		$out = array();
		while($rep = $req->fetch())
			$out[] = new Discussion($rep['ID']);
		switch(count($out)){
		case 0:	
			return NULL;
		case 1:
			return $out[0];
		default:
			return $out;
		}
	}
	
	public static function getFromName($name){
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE name=?');
		$req->execute(array($name));
		return discussionGetterOutput($req);
	}
	
	public static function getFromCreator($creator){
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE creatorID=?');
		$req->execute(array($creator->getID()));
		return discussionGetterOutput($req);
	}
	
	public static function getFromDateCreation($date){
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE dateCreation=?');
		$req->execute(array($date));
		return discussionGetterOutput($req);
	}

	public static function getFromAccessibility($accessibility){
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE creatorID=?');
		$req->execute(array($accessibility));
		return discussionGetterOutput($req);
	}
	
	public static function getCreatedLaterThan($date){
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE dateCreation>?');
		$req->execute(array($date));
		return discussionGetterOutput($req);
	}
	
	public static function getCreatedEarlierThan($date){
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions WHERE dateCreation<?');
		$req->execute(array($date));
		return discussionGetterOutput($req);
	}
	
	public static function getWhichHeCanAccess($he){
		//TODO utiliser une regex dans la requete SQL pour selectionner les discussions autorisées
		$req = $GLOBALS['bdd']->prepare('SELECT * FROM discussions');
		$req->execute(array());
		$out = array();
		while ( $rep = $req->fetch()) {
			$disc = new Discussion($rep['ID']);
			if ($disc->canAccess($membre))
				$out[] = $disc;
		}
		if($out) 
			return $out;
		else 
			return NULL;
	}
	
	// Exceptions texts
	
	//rename()
	const NAME_ALREADY_USED = 'Nom d&eacute;j&agrave; utilis&eacute;';
	const ILLEGAL_NAME = 'Le nom de la discussion est incorrect : les caract&egrave;res autoris&eacutes sont :'.
		'<br/> abcdefghijklmnopqrstuvwxyz<wbr/>ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<wbr/>'.
		'&eacute;&egrave;&agrave;&mu;_-\'()[\\]\\\\/<wbr/>,;:.&sect;!&ugrave;%&pound;$&curren;=+-*\\#~"|&ccedil;@';
	const TOO_LONG_NAME = 'Le nom est trop long : maximum 256 caract&egrave;res';
	const NAME_CHANGED = 'Le nom a bien &eacute;t&eacute; chang&eacute; !';
	
	//changeAccessibility()
	const MALFORMED_ACCESSIBILITY = 'L\'accessibilit&eacute; doit être de la forme : "p" ou "x31;41;59;26;53" ou "a42"';
	const ACCESSIBILITY_CHANGED = 'L\'accessibilit&eacute; a bien &eacute;t&eacute; chang&eacute;e !';
	
	//setDateCreation()
	const MALFORMED_DATE = 'La date de cr&eacute;ation doit &ecirc;tre de la forme "AAAA:MM:JJ hh:mm:ss"';
	const DATE_CREATION_CHANGED = 'La date de cr&eacute;ation a bien &eacute;t&eacute; chang&eacute;e';
}