<?php
class UserEvent {
	public static function sendTokenOnEmail($event) {
		$user = $event->params["user"];
		$userToken = new UserToken;
		if(!$userToken->crateEmailActivation($user)) {
			throw new CException("Unable to create user token");
		}
		$mailer = Yii::app()->mailer;
		$mailer->setFrom(Yii::app()->params["notificationEmail"], Yii::app()->params["notificationName"]);
		$mailer->Subject = Yii::t('user', 'Registration at {InstalledUrl}', array(
            '{InstalledUrl}'=> Helper::getBrandUrl(),
        ));

		$mailer->AddAddress($user->email);
		$mailer->setPathViews("application.views.mail.user");
		$mailer->setPathLayouts("application.views.mail.layouts");
		$mailer->getView("register", array(
			"name"=>Helper::mb_ucfirst($user->username),
            "user"=>$user,
			"verifyUrl"=>$event->sender->createAbsoluteUrl("user/confirm", array("t" => $userToken->type, "token"=>$userToken->token)),
		), "main");
		$mailer->AltBody=Yii::t('notification', 'Please, use mail client which support HTML markup');
		$mailer->Send();
	}

	public static function createUserServer($event) {
		$user=$event->params["user"];
		$server_id=Yii::app()->innerMail->box($user)->generateUserBoxID();
		$user->post_server_id=$server_id;
		if(!$user->save(false)) {
			throw new CException("Unable to save post user server");
		}
	}

	public static function garbageCollector($event) {
		$user=$event->params['user'];
		UserToken::model()->deleteAllByAttributes(array(
			"user_id"=>$user->id,
		));
		$onSale=Sale::model()->findAllByAttributes(array(
			"user_id"=>$user->id
		));
		foreach($onSale as $sale) {
			SaleEvent::removeFromSale($sale->website_id);
		}
	}

}