<?php
App::uses('HtmlHelper', 'View/Helper');

class CalendarHelper extends HtmlHelper
{

	public $validationErrors = array();

	private $weekDays = array();

	private $_shapes = array();
	private $_shapeLabels = array();

	/**
	 ** Copies the validationErrors variable from the View object into this instance
	 **
	 ** @param View $View The View this helper is being attached to.
	 ** @param array $settings Configuration settings for the helper.
	 **/

	public function __construct(View $View, $settings = array())
	{
		parent::__construct($View, $settings);

		if(isset($settings['shapes'])) {
				$this->_shapes = $settings['shapes'];
		}

		if(isset($settings['shapeLabels'])) {
				$this->_shapeLabels = $settings['shapeLabels'];
		}

		$this->validationErrors =& $View->validationErrors;

		$this->weekdays = array(
			__('Monday'),
			__('Tuesday'),
			__('Wednesday'),
			__('Thursday'),
			__('Friday'),
			__('Saturday'),
			__('Sunday'),
		);
	}

	public function body($date, $sortedEntries = null, $sortedEntryChildren = null)
	{
		#$this->log($dateTime->format('W')); //weeknumber starting 14
		#$this->log($dateTime->format('N')); //firstsweekday 3 for wednesday
		#$this->log($dateTime->format('t')); //number of days in this momnth

		$date = new DateTime($date['year'].'-'.$date['month'].'-'.$date['day']);
		$today = new DateTime();

		$month = $date->format('n'); $year = $date->format('Y');

		//begin date at first cell
		$date->modify('- ' . ($date->format('N') - 1) . ' days');


		$calendar = '<div class="calendar">'."\n";
		$calendar .= '<ul class="calendar-heading">'."\n";
		$calendar .= '<li class="calendar-week">'.__('Calendar Week').'</li>'."\n";

		foreach ($this->weekdays as $weekday) { $calendar .= '<li>'.$weekday.'</li>'."\n"; }

		$calendar .= '</ul><ul class="calendar-body">'."\n";

		for($cell = 1 ; $cell <= 42 ; $cell++)
		{
			// row start
			if (($cell % 7) == 1)
			{
				$calendar .= '<li class="calendar-row"><div class="calendar-week"><h5>'.$date->format('W').'</h5></div><ul class="calendar-col">'."\n";
			}

			if ($date->format('Y-n') != $year.'-'.$month)
			{
				$class = ' blank';
			}
			elseif ($date->format('Y-n-j') == $today->format('Y-n-j'))
			{
				$class = ' current';
			}
			else
			{
				$class = '';
			}

			$calendar .= '<li class="calendar-cell'.$class.'" data-rel="">';

			// cell start
			$calendar .= '<div class="date"><span class="weekDay">'.$date->format('D').',</span> '.$date->format('j').'</div>'."\n";

			// if both exist on this date give addrace array as overwrite parameter
			if(isset($sortedEntryChildren[$date->format('Y-n-j')]))
			{
				if(isset($sortedEntries[$date->format('Y-n-j')]))
				{
					$calendar .= $this->_entries($sortedEntries[$date->format('Y-n-j')], $sortedEntryChildren[$date->format('Y-n-j')]);
				}
				else
				{
					$calendar .= $this->_entries(array(), $sortedEntryChildren[$date->format('Y-n-j')]);
				}
				//$calendar .= $this->_entries($sortedEntries[$date->format('Y-n-j')]);
			}
			elseif(isset($sortedEntries[$date->format('Y-n-j')]))
			{
				$calendar .= $this->_entries($sortedEntries[$date->format('Y-n-j')]);
			}

			// cell end
			$calendar .= '</li>'."\n";

			// row end
			if (($cell  % 7) == 0)
			{
				$calendar .= "</ul></li>";
			}

			$date->modify('+1 day');
		}

		$calendar  .= '</ul></div>';

		return $calendar;
	}

	private function _entries($entries = array(), $overwrites = array())
	{
		$result = '';

		$keys = array('training', 'race', 'addrace', 'swim', 'bike', 'run', 'strength');

		foreach($keys as $key)
		{
			//if addrace program
			if(isset($overwrites[$key]) && $key === 'addrace')
			{
				$result .= $this->_program($overwrites[$key], $key, __('Race'), __('End'));
                break;
			}
			elseif(isset($entries[$key]) && $key === 'training')
			{
				$result .= $this->_program($entries[$key], $key, __('Training'), __('Start'));
			}
			elseif(isset($entries[$key]) && $key === 'race' && $entries[$key]['type'] === 'maintenance')
			{
				$result .= $this->_program($entries[$key], $key, __('Training'), __('End'));
			}
			elseif(isset($entries[$key]) && $key === 'race')
			{
				$result .= $this->_program($entries[$key], $key, __('Race'), __('End'));
			}

            $sports = array('swim', 'bike','run', 'strength');
            if(in_array($key, $sports)) {

    			if (isset($overwrites[$key]))
    			{
    				//$this->log($overwrites[$key]['date'] . ': ' . $key . ' for overwrite');
    				//if not rest
    				if(!(isset($overwrites[$key]['TassPlacementType']['value']) && $overwrites[$key]['TassPlacementType']['value'] == 'rest'))
    				{
    					$result .= $this->_workout($overwrites[$key], array('class' => 'addrace'));
    				}
    			}
    			elseif(isset($entries[$key]))
    			{
    				$result .= $this->_workout($entries[$key]);
    			}
            }
		}
		return $result;
	}

	private function _program($program, $class, $heading, $body)
	{
		$heartRate = '';

        if (isset($program['type']) && $program['type'] === 'maintenance') {
        } elseif ($class != 'training') {
			$heartRate = '
				<span class="heart-rate">
					<span class="heading"><i class="fa fa-heart"></i></span>
					<span class="body">
						<span data-min>' . $program['heart_min'] . '</span> -
						<span data-max>' . $program['heart_max'] . '</span>' . __('bpm') . '
					</span>
				</span>';
		}

    if ($class === 'addrace') {
        $url = Router::url(array('controller' => 'program_children', 'action' => 'view', $program['id']));
    } else {
        $url = Router::url(array('controller' => 'programs', 'action' => 'view', $program['id']));
    }

		return '<a href="'.$url.'" class="program program-' . $class . '">
			<span class="program-heading">
				<span class="start">' . $heading . '</span>
				<span class="icon"></span>
			</span>
			<span class="program-body">
				<span class="name">' . $program['name'] . ' - ' . $body . '</span>
				' . $heartRate . '
			</span>
		</a>';
	}

	private function _workout($workout, $options = array())
	{
		// if workout is hidden
        /*
		if (!$workout['visible'])
		{
			$options['url'] = Router::url(array('controller' => 'programs', 'action' => 'view', $workout['program_id']));
			return $this->_workoutMarkup($workout, $options);
		}
        else
        */
		// swim bike run workout
		if(in_array($workout['Sport']['value'], array('swim', 'bike', 'run', 'strength')))
		{
			$options['url'] = Router::url(array('controller' => 'workouts', 'action' => 'view', $workout['id']));
			return $this->_workoutMarkup($workout, $options);
		}
	}

	private function _workoutMarkup($workout, $options = array())
	{
		$markup = '
			<a' . $this->_workoutMarkupClass($workout, $options) . $this->_workoutMarkupAttributes($workout, $options) . '>
				<span class="workout-heading">'
					. $this->_workoutMarkupHeading($workout) .
				'</span>
				<span class="workout-body">
					' . $this->_workoutMarkupBody($workout) . '
				</span>
				<span class="workout-footer">
					' . $this->_workoutMarkupFooter($workout) . '
				</span>
			</a>';

		return $markup;
	}

	private function _workoutMarkupClass($workout, $options = array())
	{
		$classList = array();

		// general classes

		if (isset($workout['scheda']) && $workout['scheda'] == 1) {
			#array_push($classList, 'scheda-as');
		} elseif (isset($workout['scheda']) && in_array($workout['scheda'], array(25, 100))) {
			array_push($classList, 'scheda-hide');
		}


        /*
		if (!$workout['visible']) {
			array_push($classList, 'workout');
			array_push($classList, 'workout-hidden');
		} else
        */
        if(in_array($workout['Sport']['value'], array('swim', 'bike', 'run'))) {
			array_push($classList, 'workout');
			if(isset($workout['brick']) && $workout['brick'])
			{
				array_push($classList, 'workout-brick');
			} else {
				array_push($classList, 'workout-' . $workout['Sport']['value']);
				if(isset($options['class']) && $options['class'] == 'addrace') {
					array_push($classList, 'workout-addrace');
				}
			}
		} elseif ($workout['Sport']['value'] == 'strength') {
			array_push($classList, 'workout');
			array_push($classList, 'workout-strength');
			if(isset($options['class']) && $options['class'] == 'addrace') {
				array_push($classList, 'workout-addrace');
			}
		}
		return ' class="' . implode(' ', $classList) . '"';
	}

	private function _workoutMarkupAttributes($workout, $options = array())
	{
		$attributes = '';

		$attributes = isset($options['url']) ? ' href="' . $options['url'] . '"' : '';

		$shapes = array(
			0 => 'burned-out',
			25 => 'exhausted',
			50 => 'tired',
			75 => 'fatigued',
			100 => 'top-shape',
		);

		$attributes .= isset($workout['id']) ? ' data-id="' . $workout['id'] . '"' : '';
		$attributes .= isset($workout['race_id']) ? ' data-race="' . $workout['race_id'] . '"' : '';
		$attributes .= isset($workout['trainingweek']) ? ' data-trainingweek="' . $workout['trainingweek'] . '"' : '';
		$attributes .= isset($workout['zone_id']) ? ' data-zone="' . $workout['zone_id'] . '"' : '';
		$attributes .= isset($workout['year']) ? ' data-year="' . $workout['year'] . '"' : '';
		$attributes .= isset($workout['month']) ? ' data-month="' . $workout['month'] . '"' : '';
		$attributes .= isset($workout['day']) ? ' data-day="' . $workout['day'] . '"' : '';
		$attributes .= isset($workout['tass_placement_type_id']) ? ' data-tass="' . $workout['tass_placement_type_id'] . '"' : '';

		if(isset($workout['brick']) && $workout['brick'])
		{
			$attributes .= ' data-sport="brick"';
		}
		elseif(isset($workout['Sport']['value']))
		{
			$attributes .= ' data-sport="' . $workout['Sport']['value'] . '"';
		}

		return $attributes;
	}

	private function _workoutMarkupHeading($workout)
	{
		$markupStart = '<span class="name">';
		$markupEnd = '</span><span class="icon"></span>';

        /*
		if (!$workout['visible'])
		{
			return $markupStart . __('Hidden') . $markupEnd;
		}
		else
        */
        if(in_array($workout['Sport']['value'], array('swim', 'bike', 'run', 'strength')))
		{
			if(isset($workout['brick']) && $workout['brick'])
			{
				return $markupStart . __('Brick') . $markupEnd;
			}
			else
			{
				return $markupStart . __( $workout['Sport']['name'] ) . $markupEnd;
			}
		}
	}

	private function _workoutMarkupBody($workout)
	{
		$body = array();

        /*
		if (!$workout['visible'])
		{
			return 'Unhide workout';
		}
        */

		if(isset($workout['StrengthType']['value'] ))
		{
			$body['zone'] = '<span class="zone">' . $workout['StrengthType']['name'] . '</span>';
		}
		elseif(isset($workout['Zone']['value'] ))
		{
			if(isset($workout['scheda']) && $workout['scheda'] == 1) {
				$body['zone'] = '<span class="zone">' . __('Aerobic Stimulation') . '</span>';
			} else {
				$body['zone'] = '<span class="zone">' .__( $workout['Zone']['name'] ) . '</span>';
			}
		}

		if (isset($workout['adjustment']) && $workout['adjustment'])
		{
			$body['value'] =
			'<span class="value adjusted '. (($workout['Sport']['Measurement']['value'] == 'time') ? 'time' : 'distance' ). '">
    	' . (($workout['Sport']['Measurement']['value'] == 'time') ? gmdate("H:i", $workout['adjustment'] * 60) : $workout['adjustment']) . '
			</span>';
		}
		elseif (isset($workout['value']))
		{
			$body['value'] =
			'<span class="value '. (($workout['Sport']['Measurement']['value'] == 'time') ? 'time' : 'distance' ). '">
    	' . (($workout['Sport']['Measurement']['value'] == 'time') ? gmdate("H:i", $workout['value'] * 60) : $workout['value']) . '
			</span>';
		}

		if (isset($workout['brick']))
		{
			$body['brick'] =
			'<span class="'. (($workout['Sport']['Measurement']['value'] == 'time') ? 'time' : 'distance' ). ' value-brick">
    	' . (($workout['Sport']['Measurement']['value'] == 'time') ? gmdate("H:i", $workout['brick'] * 60) : $workout['value']) . '
			</span>	';
		}

		if (isset($workout['heart_min']) && isset($workout['heart_min']))
		{
			$body['heartRate'] =
			'<span class="heart-rate">
				<span class="heading"><i class="fa fa-heart"></i></span>
				<span class="body"><span class="heart-min">' . $workout['heart_min'] . '</span> - <span class="heart-max">' . $workout['heart_max'] . '</span> ' . __('bpm') . '</span>
			</span>';
		}

		return implode("\n", $body);
	}

	private function _workoutMarkupFooter($workout)
	{
		$footer = array();
		$class = '';
		#$attributes .= isset($workout['complete']) ? ' data-complete="' . $workout['complete'] . '"' : '';
		#$attributes .= isset($workout['shape']) ? ' data-shape="' . $shapes[$workout['shape']] . '"' : '';

        //if shape has null value but the other exist
        if(isset($workout['shape'])) {
            if (is_null($workout['shape']) && isset($workout['complete'])) {
                $workout['shape'] = 100;
            }
        }

        if(isset($workout['complete'])) {
            if (isset($workout['shape']) && is_null($workout['complete'])) {
                $workout['complete'] = 100;
            }
        }

		$shape = '<span data-shape="';
		if (isset($workout['shape'])) {
			$class = ' show-adjust';
			$shape .= $workout['shape'] . '" class="shape ' . $this->_shapes[$workout['shape']] . '"';

		} elseif (isset($workout['complete'])) {
			$shape .= '100" class="shape ' . end($this->_shapes) . '"';
		} else {
			$shape .= '" class="shape"';
		}

		$shape .= '></span>';

		$complete = '<span class="complete" data-complete="';
		if (isset($workout['complete'])) {
			$class = ' show-adjust';
			$complete .= $workout['complete'] . '">' . $workout['complete'];
		} elseif (isset($workout['shape'])) {
			$complete.= '100">100';
		} else {
			$complete.= '">';
		}

		$complete .= '% ' . __('Complete') . '</span>';

		$footer['adjustment'] = '<span class="adjustment' . $class . '">' . $shape . $complete . '</span>';

		return implode("\n", $footer);
	}

	public function preview($workoutPlacements, $weekDays)
	{
		$render = '<div class="calendar preview">'."\n";
		$render .= '<ul class="calendar-heading">'."\n";
		foreach ($weekDays as  $weekDay)
		{
			$render .= '<li>' . __( $weekDay ) . '</li>'."\n";
		}
		$render .= '</ul><ul class="calendar-body">'."\n";
		$render .= '<li class="calendar-row"><ul class="calendar-col">'."\n";

		foreach ($weekDays as $day => $weekDay)
		{
			$render .= '<li class="calendar-cell weekday-'.$day.'">';

			$render .= '<div class="weekday-preview">'.$weekDay.'</div>';

			foreach ($workoutPlacements as $key => $workoutPlacement)
			{
				if($workoutPlacement['WorkoutPlacement']['week_day'] == $day)
				{
					$url = Router::url(array('action' => 'step4', $key ));
					if (isset($workoutPlacement['Zone']['name']))
					{
						$zone = $workoutPlacement['Zone']['name'];
					}
					elseif ($workoutPlacement['Sport']['value'] != 'strength')
					{
						$zone = __('Speed');
					}
					else
					{
						$zone = '';
					}

					$render .= '
						<a class="workout workout-'.$workoutPlacement['Sport']['value'].'" href="'.$url.'" data-key="'.$key.'" data-weekday="'.$workoutPlacement['WorkoutPlacement']['week_day'].'">
							<span class="workout-heading">
								<span class="sport">
									<span class="name">' . __( $workoutPlacement['Sport']['name'] ) . '</span>
									<span class="icon"></span>
								</span>
							</span>
							<span class="workout-body">
								<span class="zone">' . __( $zone ) . '</span>
							</span>
						</span></a>';
				}
			}

			$render .= '</li>'."\n";
		}
		$render .= "</ul></li>";
		$render .= '</ul></div>';

		return $render;
	}

	public function header($date)
	{
		$dateTime = mktime(0,0,0, $date['month'], 1, $date['year']);
			$datePrevious = strtotime ( '-1 month' , $dateTime) ;
			$dateNext = strtotime ( '+1 month' , $dateTime) ;
			$render =
			'<div class="row">
				<div class="col-sm-4 col-xs-4">
					'.$this->link('<i class="fa fa-chevron-left"></i> <span class="hidden-xs">'.__('Previous').'</span>', array( getdate($datePrevious)['year'], getdate($datePrevious)['mon']), array('class' => 'btn btn-block btn-default', 'escape' => false)).'
				</div>
				<div class="col-sm-4 col-xs-4">
					<div class="text-center">
						<h4>'. __( DateTime::createFromFormat('!m', $date['month'])->format('F') ) . ' ' . $date['year'] . '</h4>
					</div>
				</div>
				<div class="col-sm-4 col-xs-4">
					'.$this->link('<span class="hidden-xs">'.__('Next').'</span> <i class="fa fa-chevron-right"></i>' , array( getdate($dateNext)['year'], getdate($dateNext)['mon']), array('class' => 'btn btn-block btn-default', 'escape' => false)).'
				</div>
			</div>';

			return $render;
	}

	public function footer($date)
	{
		$dateTime = mktime(0,0,0, $date['month'], 1, $date['year']);
			$datePrevious = strtotime ( '-1 month' , $dateTime) ;
			$dateNext = strtotime ( '+1 month' , $dateTime) ;
			$render =
			'<div class="row">
				<div class="col-sm-6 col-xs-6">
					'.$this->link('<i class="fa fa-chevron-left"></i> <span class="hidden-xs">'.__('Previous').'</span>', array( getdate($datePrevious)['year'], getdate($datePrevious)['mon']), array('class' => 'btn btn-block btn-default', 'escape' => false)).'
				</div>
				<div class="col-sm-6 col-xs-6">
					'.$this->link('<span class="hidden-xs">'.__('Next').'</span> <i class="fa fa-chevron-right"></i>' , array( getdate($dateNext)['year'], getdate($dateNext)['mon']), array('class' => 'btn btn-block btn-default', 'escape' => false)).'
				</div>
			</div>';

			return $render;
	}
}
?>
