<?php

class Tracks extends Model
{

	function __construct($fromArray = array())
	{
		$this->_tableName_ = 'tracks';
		parent::__construct($fromArray);
		$this->setRelation('points', 'id', 'TrackPoints', 'trackId', self::TO_MANY, '`id` ASC');
	}

	static function model()
	{
		return new self();
	}

	function distance()
	{
		return Geo::formatedDistance($this->distance);
	}

	/**
	 * Считает/пересчитывает длину фрагмента трека и сохраняет значение в БД.
	 */
	function calculateDist()
	{
		$points = $this->points;
		$distance = 0;
		$prevPoint = array();
		foreach ($points as $point) {
			if ($prevPoint) {
				$distance += Geo::distance(
						$prevPoint,
						array('lat' => floatval($point->lat), 'lng' => floatval($point->lng), 'alt' => floatval($point->alt)));
			}

			$prevPoint = array(
				'lat' => floatval($point->lat),
				'lng' => floatval($point->lng),
				'alt' => floatval($point->alt),
			);
		}
		$this->distance = $distance;
		$this->save();

		return $distance;
	}

}
