<?php
class WeightReading extends DBObject implements JsonSerializable  {

	/**
	 * @var IUserSettingsRepository
	 */
	private $_userSettingsRepo;

	public static function CalculateBMI($weight, $height){
		if ($weight==0 || $height==0)
			return 0;
		return ($weight/$height)/$height;
	}
	
	public function __construct(IUserSettingsRepository $userSettingsRepo, $id=0) {
		parent::__construct("weight_readings", "reading_id", $id);
		$this->_userSettingsRepo=$userSettingsRepo;
	}
	
	public function GetParsedDate(){
		return date_parse($this->Timestamp);
	}
	
	public function Save(User $user=null) {
		if ($user==null)
			throw new Exception("Please specify user");
		$height=$this->_userSettingsRepo->GetSetting($user, "height")->Value;
		$height*=0.01;//convert from cm to metres;
		$this->Bmi=self::CalculateBMI($this->Weight, $height);
		$this->UserId=$user->UserId;
		parent::Save();
	}
	
	public function jsonSerialize() {
		$output=new stdClass();
		$output->id=(int)$this->ReadingId;
		$output->date=date("c", strtotime($this->Timestamp));
		$output->weight=(float)$this->Weight;
		$output->bmi=(float)$this->Bmi;
		$output->fat=(float)$this->Fat;
        return $output;
    }
}
