<?php
ApplicationSettings::RegisterDefaultSetting("weight", "graph_history_duration", "1M");

class Weight extends Controller {
	private function GetUserReadings(IWeightReadingRepository $weightReadingRepo, IUserSettingsRepository $userSettingRepo){
		$user=Session::GetLoggedInUser();
		$graphDuration=ApplicationSettings::GetSetting("weight", "graph_history_duration");
		$userDurationSetting=$userSettingRepo->GetSetting($user, "weight_graph_duration")->Value;
		if ($userDurationSetting!=null)
			$graphDuration=$userDurationSetting.'M';
		
		$dateTo=new DateTime();
		$dateFrom=clone $dateTo;
		$dateFrom->sub(new DateInterval("P".$graphDuration));
		return $weightReadingRepo->GetReadingsInDateRange($user->UserId,$dateFrom,$dateTo);
	}
	
	public function Index(IWeightReadingRepository $weightReadingRepo, IUserSettingsRepository $userSettingRepo) {
		return new View("Weight/index.view",array("readings"=>$this->GetUserReadings($weightReadingRepo, $userSettingRepo)));
	}
	
	public function GetReadings(IWeightReadingRepository $weightReadingRepo, IUserSettingsRepository $userSettingRepo) {
		return json_encode($this->GetUserReadings($weightReadingRepo, $userSettingRepo));
	}
	
	public function Add($weight, $fat, IUserSettingsRepository $userSettingsRepo){
		$reading=new WeightReading($userSettingsRepo);
		
		foreach (array($weight,$fat) as $arg)
			if ($arg=="" || $arg<=0)
				return;

		$reading->Weight=$weight;
		$reading->Fat=$fat;
		$reading->Save(Session::GetLoggedInUser());
		
		return json_encode($reading);
	}
	
	public function Delete($id,IWeightReadingRepository $weightReadingRepo){
		$weightReadingRepo->Delete($id);
	}
}
