<?php
/*
** Zabbix
** Copyright (C) 2001-2023 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


/**
 * General class for SVG Graph usage.
 */
class CSvgGraph extends CSvg {

	const SVG_GRAPH_X_AXIS_HEIGHT = 20;
	const SVG_GRAPH_DEFAULT_COLOR = '#b0af07';
	const SVG_GRAPH_DEFAULT_TRANSPARENCY = 5;
	const SVG_GRAPH_DEFAULT_POINTSIZE = 1;
	const SVG_GRAPH_DEFAULT_LINE_WIDTH = 1;

	const SVG_GRAPH_X_AXIS_LABEL_MARGIN = 5;
	const SVG_GRAPH_Y_AXIS_LEFT_LABEL_MARGIN = 5;
	const SVG_GRAPH_Y_AXIS_RIGHT_LABEL_MARGIN = 12;

	protected $canvas_height;
	protected $canvas_width;
	protected $canvas_x;
	protected $canvas_y;

	/**
	 * Problems annotation labels color.
	 *
	 * @var string
	 */
	protected $color_annotation = '#AA4455';

	/**
	 * Text color.
	 *
	 * @var string
	 */
	protected $text_color;

	/**
	 * Grid color.
	 *
	 * @var string
	 */
	protected $grid_color;

	/**
	 * Array of graph metrics data.
	 *
	 * @var array
	 */
	protected $metrics = [];

	/**
	 * Array of graph points data. Calculated from metrics data.
	 *
	 * @var array
	 */
	protected $points = [];

	/**
	 * Array of metric paths. Where key is metric index from $metrics array.
	 *
	 * @var array
	 */
	protected $paths = [];

	/**
	 * Array of graph problems to display.
	 *
	 * @var array
	 */
	protected $problems = [];

	protected $max_value_left = null;
	protected $max_value_right = null;
	protected $min_value_left = null;
	protected $min_value_right = null;

	protected $left_y_show = false;
	protected $left_y_min = null;
	protected $left_y_max = null;
	protected $left_y_units = null;
	protected $left_y_empty = true;

	protected $right_y_show = false;
	protected $right_y_min = null;
	protected $right_y_max = null;
	protected $right_y_units = null;
	protected $right_y_empty = true;

	protected $right_y_zero = null;
	protected $left_y_zero = null;

	protected $x_show;

	protected $offset_bottom;

	/**
	 * Value for graph left offset. Is used as width for left Y axis container.
	 *
	 * @var int
	 */
	protected $offset_left = 20;

	/**
	 * Value for graph right offset. Is used as width for right Y axis container.
	 *
	 * @var int
	 */
	protected $offset_right = 20;

	/**
	 * Maximum width of container for every Y axis.
	 *
	 * @var int
	 */
	protected $max_yaxis_width = 120;

	protected $offset_top;
	protected $time_from;
	protected $time_till;

	/**
	 * Height for X axis container.
	 *
	 * @var int
	 */
	protected $xaxis_height = 20;

	/**
	 * SVG default size.
	 */
	protected $width = 1000;
	protected $height = 1000;

	public function __construct(array $options) {
		parent::__construct();

		// Set colors.
		$theme = getUserGraphTheme();
		$this->text_color = '#' . $theme['textcolor'];
		$this->grid_color = '#' . $theme['gridcolor'];

		$this
			->addClass(ZBX_STYLE_SVG_GRAPH)
			->setTimePeriod($options['time_period']['time_from'], $options['time_period']['time_to'])
			->setXAxis($options['x_axis'])
			->setYAxisLeft($options['left_y_axis'])
			->setYAxisRight($options['right_y_axis']);
	}

	/**
	 * Get graph canvas X offset.
	 *
	 * @return int
	 */
	public function getCanvasX() {
		return $this->canvas_x;
	}

	/**
	 * Get graph canvas Y offset.
	 *
	 * @return int
	 */
	public function getCanvasY() {
		return $this->canvas_y;
	}

	/**
	 * Get graph canvas width.
	 *
	 * @return int
	 */
	public function getCanvasWidth() {
		return $this->canvas_width;
	}

	/**
	 * Get graph canvas height.
	 *
	 * @return int
	 */
	public function getCanvasHeight() {
		return $this->canvas_height;
	}

	/**
	 * Set problems data for graph.
	 *
	 * @param array $problems  Array of problems data.
	 *
	 * @return CSvgGraph
	 */
	public function addProblems(array $problems) {
		$this->problems = $problems;

		return $this;
	}

	/**
	 * Set metrics data for graph.
	 *
	 * @param array $metrics  Array of metrics data.
	 *
	 * @return CSvgGraph
	 */
	public function addMetrics(array $metrics = []) {
		$metrics_for_each_axes = [
			GRAPH_YAXIS_SIDE_LEFT => 0,
			GRAPH_YAXIS_SIDE_RIGHT => 0
		];

		foreach ($metrics as $i => $metric) {
			$min_value = null;
			$max_value = null;

			if ($metric['points']) {
				$metrics_for_each_axes[$metric['options']['axisy']]++;

				foreach ($metric['points'] as $point) {
					if ($min_value === null || $min_value > $point['value']) {
						$min_value = $point['value'];
					}
					if ($max_value === null || $max_value < $point['value']) {
						$max_value = $point['value'];
					}

					$this->points[$i][$point['clock']] = $point['value'];
				}

				if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_LEFT) {
					if ($this->min_value_left === null || $this->min_value_left > $min_value) {
						$this->min_value_left = $min_value;
					}
					if ($this->max_value_left === null || $this->max_value_left < $max_value) {
						$this->max_value_left = $max_value;
					}
				}
				else {
					if ($this->min_value_right === null || $this->min_value_right > $min_value) {
						$this->min_value_right = $min_value;
					}
					if ($this->max_value_right === null || $this->max_value_right < $max_value) {
						$this->max_value_right = $max_value;
					}
				}
			}

			$this->metrics[$i] = [
				'name' => $metric['hosts'][0]['name'].NAME_DELIMITER.$metric['name'],
				'itemid' => $metric['itemid'],
				'units' => $metric['units'],
				'host' => $metric['hosts'][0],
				'options' => ['order' => $i] + $metric['options']
			];
		}

		$this->left_y_empty = ($metrics_for_each_axes[GRAPH_YAXIS_SIDE_LEFT] == 0);
		$this->right_y_empty = ($metrics_for_each_axes[GRAPH_YAXIS_SIDE_RIGHT] == 0);

		return $this;
	}

	/**
	 * Set graph time period.
	 *
	 * @param int $time_from  Timestamp.
	 * @param int @time_till  Timestamp.
	 *
	 * @return CSvgGraph
	 */
	public function setTimePeriod($time_from, $time_till) {
		$this->time_from = $time_from;
		$this->time_till = $time_till;

		return $this;
	}

	/**
	 * Set left side Y axis display options.
	 *
	 * @param array  $options
	 * @param int    $options['show']
	 * @param string $options['min']
	 * @param string $options['max']
	 * @param string $options['units']
	 *
	 * @return CSvgGraph
	 */
	public function setYAxisLeft(array $options) {
		$this->left_y_show = ($options['show'] == SVG_GRAPH_AXIS_SHOW);

		if ($options['min'] !== '') {
			$this->left_y_min = $options['min'];
		}
		if ($options['max'] !== '') {
			$this->left_y_max = $options['max'];
		}
		if ($options['units'] !== null) {
			$this->left_y_units = trim(preg_replace('/\s+/', ' ', $options['units']));
		}

		return $this;
	}

	/**
	 * Set right side Y axis display options.
	 *
	 * @param array  $options
	 * @param int    $options['show']
	 * @param string $options['min']
	 * @param string $options['max']
	 * @param string $options['units']
	 *
	 * @return CSvgGraph
	 */
	public function setYAxisRight(array $options) {
		$this->right_y_show = ($options['show'] == SVG_GRAPH_AXIS_SHOW);

		if ($options['min'] !== '') {
			$this->right_y_min = $options['min'];
		}
		if ($options['max'] !== '') {
			$this->right_y_max = $options['max'];
		}
		if ($options['units'] !== null) {
			$this->right_y_units = trim(preg_replace('/\s+/', ' ', $options['units']));
		}

		return $this;
	}

	/**
	 * Show or hide X axis.
	 *
	 * @param array $options
	 *
	 * @return CSvgGraph
	 */
	public function setXAxis(array $options) {
		$this->x_show = ($options['show'] == SVG_GRAPH_AXIS_SHOW);

		return $this;
	}

	/**
	 * Return array of horizontal labels with positions. Array key will be position, value will be label.
	 *
	 * @return array
	 */
	public function getTimeGridWithPosition() {
		$period = $this->time_till - $this->time_from;
		$step = round(bcmul(bcdiv($period, $this->canvas_width), 100)); // Grid cell (100px) in seconds.

		/*
		 * In case if requested time period is so small that it is rounded to zero, we are displaying only two
		 * milestones on X axis - the start and the end of period.
		 */
		if ($step == 0) {
			return [
				0 => zbx_date2str(TIME_FORMAT_SECONDS, $this->time_from),
				$this->canvas_width => zbx_date2str(TIME_FORMAT_SECONDS, $this->time_till)
			];
		}

		$start = $this->time_from + $step - $this->time_from % $step;
		$time_formats = [
			SVG_GRAPH_DATE_FORMAT,
			SVG_GRAPH_DATE_FORMAT_SHORT,
			SVG_GRAPH_DATE_TIME_FORMAT_SHORT,
			TIME_FORMAT,
			TIME_FORMAT_SECONDS
		];

		// Search for most appropriate time format.
		foreach ($time_formats as $fmt) {
			$grid_values = [];

			for ($clock = $start; $this->time_till >= $clock; $clock += $step) {
				$relative_pos = round($this->canvas_width - $this->canvas_width * ($this->time_till - $clock) / $period);
				$grid_values[$relative_pos] = zbx_date2str($fmt, $clock);
			}

			/**
			 * If at least two calculated time-strings are equal, proceed with next format. Do that as long as each date
			 * is different or there is no more time formats to test.
			 */
			if (count(array_flip($grid_values)) == count($grid_values) || $fmt === end($time_formats)) {
				break;
			}
		}

		return $grid_values;
	}

	/**
	 * Add UI selection box element to graph.
	 *
	 * @return CSvgGraph
	 */
	public function addSBox() {
		$this->addItem([
			(new CSvgRect(0, 0, 0, 0))->addClass('svg-graph-selection'),
			(new CSvgText(0, 0, ''))->addClass('svg-graph-selection-text')
		]);

		return $this;
	}

	/**
	 * Add UI helper line that follows mouse.
	 *
	 * @return CSvgGraph
	 */
	public function addHelper() {
		$this->addItem((new CSvgLine(0, 0, 0, 0))->addClass(CSvgTag::ZBX_STYLE_GRAPH_HELPER));

		return $this;
	}

	/**
	 * Render graph.
	 *
	 * @return CSvgGraph
	 */
	public function draw() {
		$this->applyMissingDataFunc();
		$this->calculateDimensions();

		if ($this->canvas_width > 0 && $this->canvas_height > 0) {
			$this->calculatePaths();

			$this->drawGrid();

			if ($this->left_y_show) {
				$this->drawCanvasLeftYAxis();
			}
			if ($this->right_y_show) {
				$this->drawCanvasRightYAxis();
			}
			if ($this->x_show) {
				$this->drawCanvasXAxis();
			}

			$this->drawMetricsLine();
			$this->drawMetricsPoint();

			$this->drawProblems();

			$this->addClipArea();
		}

		return $this;
	}

	/**
	 * Add dynamic clip path to hide metric lines and area outside graph canvas.
	 */
	protected function addClipArea() {
		$areaid = uniqid('metric_clip_');

		// CSS styles.
		$this->styles['.'.CSvgTag::ZBX_STYLE_GRAPH_AREA]['clip-path'] = 'url(#'.$areaid.')';
		$this->styles['[data-metric]']['clip-path'] = 'url(#'.$areaid.')';

		$this->addItem(
			(new CsvgTag('clipPath'))
				->addItem(
					(new CSvgPath(implode(' ', [
						'M'.$this->canvas_x.','.($this->canvas_y - 3),
						'H'.($this->canvas_width + $this->canvas_x),
						'V'.($this->canvas_height + $this->canvas_y),
						'H'.($this->canvas_x)
					])))
				)
				->setAttribute('id', $areaid)
		);
	}

	/**
	 * Calculate canvas size, margins and offsets for graph canvas inside SVG element.
	 */
	protected function calculateDimensions() {
		// Canvas height must be specified before call self::getValuesGridWithPosition.
		$this->offset_top = 10;
		$this->offset_bottom = self::SVG_GRAPH_X_AXIS_HEIGHT;
		$this->canvas_height = $this->height - $this->offset_top - $this->offset_bottom;
		$this->canvas_y = $this->offset_top;

		// Set missing properties for left Y axis.
		if ($this->left_y_min === null) {
			$this->left_y_min = $this->min_value_left ? : 0;
		}
		if ($this->left_y_max === null) {
			$this->left_y_max = $this->max_value_left ? : 1;
		}

		if (bccomp($this->left_y_min, $this->left_y_max) == 0) {
			$this->left_y_min -= 0.5;
			$this->left_y_max += 0.5;
		}
		elseif (bccomp($this->left_y_min, $this->left_y_max) == 1) {
			$this->left_y_max = $this->left_y_min + 1;
		}

		$grid = $this->getValueGrid($this->left_y_min, $this->left_y_max);
		$this->left_y_min = $grid[0];
		$this->left_y_max = end($grid);

		if ($this->left_y_units === null) {
			$this->left_y_units = '';
			foreach ($this->metrics as $metric) {
				if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_LEFT) {
					$this->left_y_units = $metric['units'];
					break;
				}
			}
		}

		// Set missing properties for right Y axis.
		if ($this->right_y_min === null) {
			$this->right_y_min = $this->min_value_right ? : 0;
		}
		if ($this->right_y_max === null) {
			$this->right_y_max = $this->max_value_right ? : 1;
		}

		if (bccomp($this->right_y_min, $this->right_y_max) == 0) {
			$this->right_y_min -= 0.5;
			$this->right_y_max += 0.5;
		}
		elseif (bccomp($this->right_y_min, $this->right_y_max) == 1) {
			$this->right_y_max = $this->right_y_min + 1;
		}

		$grid = $this->getValueGrid($this->right_y_min, $this->right_y_max);
		$this->right_y_min = $grid[0];
		$this->right_y_max = end($grid);

		if ($this->right_y_units === null) {
			$this->right_y_units = '';
			foreach ($this->metrics as $metric) {
				if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) {
					$this->right_y_units = $metric['units'];
					break;
				}
			}
		}

		// Define canvas dimensions and offsets, except canvas height and bottom offset.
		$approx_width = 10;

		if ($this->left_y_show) {
			$values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_LEFT, $this->left_y_empty);

			if ($values) {
				$offset_left = max($this->offset_left, max(array_map('strlen', $values)) * $approx_width);
				$this->offset_left = (int) min($offset_left, $this->max_yaxis_width);
			}
		}

		if ($this->right_y_show) {
			$values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_RIGHT, $this->right_y_empty);

			if ($values) {
				$offset_right = max($this->offset_right, max(array_map('strlen', $values)) * $approx_width);
				$offset_right += self::SVG_GRAPH_Y_AXIS_RIGHT_LABEL_MARGIN;
				$this->offset_right = (int) min($offset_right, $this->max_yaxis_width);
			}
		}

		$this->canvas_width = $this->width - $this->offset_left - $this->offset_right;
		$this->canvas_x = $this->offset_left;

		// Calculate Y = 0 position.
		$delta = (($this->right_y_max - $this->right_y_min) ? : 1);
		$this->right_y_zero = $this->canvas_y + $this->canvas_height * $this->right_y_max / $delta;

		$delta = (($this->left_y_max - $this->left_y_min) ? : 1);
		$this->left_y_zero = $this->canvas_y + $this->canvas_height * $this->left_y_max / $delta;
	}

	/**
	 * Get array of X points with labels, for grid and X/Y axes. Array key is Y coordinate for SVG, value is label with
	 * axis units.
	 *
	 * @param int $side  Type of X axis: GRAPH_YAXIS_SIDE_RIGHT, GRAPH_YAXIS_SIDE_LEFT
	 *
	 * @return array
	 */
	protected function getValuesGridWithPosition($side, $empty_set = false) {
		if ($empty_set) {
			$units = '';
		}
		elseif ($side === GRAPH_YAXIS_SIDE_LEFT) {
			$min_value = $this->left_y_min;
			$max_value = $this->left_y_max;
			$units = $this->left_y_units;
		}
		else {
			$min_value = $this->right_y_min;
			$max_value = $this->right_y_max;
			$units = $this->right_y_units;
		}

		$grid = $empty_set ? [0, 1] : $this->getValueGrid($min_value, $max_value);
		$min_value = $grid[0];
		$max_value = end($grid);
		$delta = ($max_value != $min_value)
			? $max_value - $min_value
			: (count($grid) > 1 ? end($grid) - $grid[0] : 1);
		$grid_values = [];

		foreach ($grid as $value) {
			$relative_pos = $this->canvas_height - intval($this->canvas_height * ($max_value - $value) / $delta);

			if ($relative_pos >= 0 && $relative_pos <= $this->canvas_height) {
				$grid_values[$relative_pos] = convert_units([
					'value' => $value,
					'units' => $units,
					'convert' => ITEM_CONVERT_NO_UNITS
				]);
			}
		}

		return $grid_values;
	}

	/**
	 * Add Y axis with labels to left side of graph.
	 */
	protected function drawCanvasLeftYaxis() {
		$grid_values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_LEFT, $this->left_y_empty);
		$this->addItem(
			(new CSvgGraphAxis($grid_values, GRAPH_YAXIS_SIDE_LEFT))
				->setSize($this->offset_left, $this->canvas_height)
				->setPosition($this->canvas_x - $this->offset_left, $this->canvas_y)
				->setTextColor($this->text_color)
				->setLineColor($this->grid_color)
		);
	}

	/**
	 * Add Y axis with labels to right side of graph.
	 */
	protected function drawCanvasRightYAxis() {
		$grid_values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_RIGHT, $this->right_y_empty);

		// Do not draw label at the bottom of right Y axis to avoid label averlapping with horizontal axis arrow.
		if (array_key_exists(0, $grid_values)) {
			unset($grid_values[0]);
		}

		$this->addItem(
			(new CSvgGraphAxis($grid_values, GRAPH_YAXIS_SIDE_RIGHT))
				->setSize($this->offset_right, $this->canvas_height)
				->setPosition($this->canvas_x + $this->canvas_width, $this->canvas_y)
				->setTextColor($this->text_color)
				->setLineColor($this->grid_color)
		);
	}

	/**
	 * Add X axis with labels to graph.
	 */
	protected function drawCanvasXAxis() {
		$this->addItem(
			(new CSvgGraphAxis($this->getTimeGridWithPosition(), GRAPH_YAXIS_SIDE_BOTTOM))
				->setSize($this->canvas_width, $this->xaxis_height)
				->setPosition($this->canvas_x, $this->canvas_y + $this->canvas_height)
				->setTextColor($this->text_color)
				->setLineColor($this->grid_color)
		);
	}

	/**
	 * Calculate array of points between $min and $max value.
	 *
	 * @param int $min  Minimum value.
	 * @param int $max  Maximum value.
	 *
	 * @return $array
	 */
	protected function getValueGrid($min, $max) {
		$res = [];

		// If absolute min/max is equal, calculate grid with 4 rows to make 0 centered. 5 rows otherwise.
		$grid_rows = (abs($min) == abs($max)) ? 4 : 5;
		$decimals = strlen(substr(strrchr($max, '.'), 1));
		$decimals = $decimals > 4 ? 4 : $decimals;
		$decimals = $decimals < 2 ? 2 : $decimals;
		for ($base = 10; $base > .01; $base /= 10) {
			$mul = ($max > 0) ? 1 / pow($base, floor(log10($max))) : 1;
			$max10 = ceil($mul * $max) / $mul;
			$min10 = floor($mul * $min) / $mul;
			$delta = $max10 - $min10;
			$delta = ceil($mul * $delta) / $mul;

			if ($mul >= 1) {
				if ($delta) {
					for ($i = 0; $delta >= $i; $i += $delta / $grid_rows) {
						$res[] = sprintf('%.'.$decimals.'f', $i + $min10);
					}
				}
				else {
					$res[] = $min10;
				}
				break;
			}
		}

		return $res;
	}

	/**
	 * Add grid to graph.
	 */
	protected function drawGrid() {
		$time_points = $this->x_show ? $this->getTimeGridWithPosition() : [];
		$value_points = [];

		if ($this->left_y_show) {
			$value_points = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_LEFT, $this->left_y_empty);

			unset($time_points[0]);
		}
		elseif ($this->right_y_show) {
			$value_points = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_RIGHT, $this->right_y_empty);

			unset($time_points[$this->canvas_width]);
		}

		if ($this->x_show) {
			unset($value_points[0]);
		}

		$this->addItem((new CSvgGraphGrid($value_points, $time_points))
			->setPosition($this->canvas_x, $this->canvas_y)
			->setSize($this->canvas_width, $this->canvas_height)
			->setColor($this->grid_color)
		);
	}

	/**
	 * Calculate paths for metric elements.
	 */
	protected function calculatePaths() {
		// Metric having very big values of y outside visible area will fail to render.
		$y_max = pow(2, 16);
		$y_min = $y_max * -1;

		foreach ($this->metrics as $index => $metric) {
			if (!array_key_exists($index, $this->points)) {
				continue;
			}

			if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) {
				$min_value = $this->right_y_min;
				$max_value = $this->right_y_max;
			}
			else {
				$min_value = $this->left_y_min;
				$max_value = $this->left_y_max;
			}

			$time_range = ($this->time_till - $this->time_from) ? : 1;
			$value_diff = ($max_value - $min_value) ? : 1;
			$timeshift = $metric['options']['timeshift'];
			$paths = [];

			$path_num = 0;
			foreach ($this->points[$index] as $clock => $point) {
				// If missing data function is SVG_GRAPH_MISSING_DATA_NONE, path should be split in multiple svg shapes.
				if ($point === null) {
					$path_num++;
					continue;
				}

				/**
				 * Avoid invisible data point drawing. Data sets of type != SVG_GRAPH_TYPE_POINTS cannot be skipped to
				 * keep shape unchanged.
				 */
				$in_range = ($max_value >= $point && $min_value <= $point);
				if ($in_range || $metric['options']['type'] != SVG_GRAPH_TYPE_POINTS) {
					$x = $this->canvas_x + $this->canvas_width
						- $this->canvas_width * ($this->time_till - $clock + $timeshift) / $time_range;
					$y = $this->canvas_y + $this->canvas_height * ($max_value - $point) / $value_diff;

					if (!$in_range) {
						$y = ($point > $max_value) ? max($y_min, $y) : min($y_max, $y);
					}

					$paths[$path_num][] = [$x, ceil($y), convert_units([
						'value' => $point,
						'units' => $metric['units']
					])];
				}
			}

			if ($paths) {
				$this->paths[$index] = $paths;
			}
		}
	}

	/**
	 * Modifies metric data and Y value range according specified missing data function.
	 */
	protected function applyMissingDataFunc() {
		foreach ($this->metrics as $index => $metric) {
			/**
			 * - Missing data points are calculated only between existing data points;
			 * - Missing data points are not calculated for SVG_GRAPH_TYPE_POINTS metrics;
			 * - SVG_GRAPH_MISSING_DATA_CONNECTED is default behavior of SVG graphs, so no need to calculate anything
			 *   here.
			 */
			if (array_key_exists($index, $this->points)
					&& $metric['options']['type'] != SVG_GRAPH_TYPE_POINTS
					&& $metric['options']['missingdatafunc'] != SVG_GRAPH_MISSING_DATA_CONNECTED) {
				$points = &$this->points[$index];
				$missing_data_points = $this->getMissingData($points, $metric['options']['missingdatafunc']);

				// Sort according new clock times (array keys).
				$points += $missing_data_points;
				ksort($points);

				// Missing data function can change min value of Y axis.
				if ($missing_data_points
						&& $metric['options']['missingdatafunc'] == SVG_GRAPH_MISSING_DATA_TREAT_AS_ZERO) {
					if ($this->min_value_left > 0 && $metric['options']['axisy'] == GRAPH_YAXIS_SIDE_LEFT) {
						$this->min_value_left = 0;
					}
					elseif ($this->min_value_right > 0 && $metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) {
						$this->min_value_right = 0;
					}
				}
			}
		}
	}

	/**
	 * Calculate missing data for given set of $points according given $missingdatafunc.
	 *
	 * @param array $points           Array of metric points to modify, where key is metric timestamp.
	 * @param int   $missingdatafunc  Type of function, allowed value:
	 *                                SVG_GRAPH_MISSING_DATA_TREAT_AS_ZERO, SVG_GRAPH_MISSING_DATA_NONE,
	 *                                SVG_GRAPH_MISSING_DATA_CONNECTED
	 *
	 * @return array  Array of calculated missing data points.
	 */
	protected function getMissingData(array $points = [], $missingdatafunc) {
		// Get average distance between points to detect gaps of missing data.
		$prev_clock = null;
		$points_distance = [];
		foreach ($points as $clock => $point) {
			if ($prev_clock !== null) {
				$points_distance[] = $clock - $prev_clock;
			}
			$prev_clock = $clock;
		}

		/**
		 * $threshold          is a minimal period of time at what we assume that data point is missed;
		 * $average_distance   is an average distance between existing data points;
		 * $gap_interval       is a time distance between missing points used to fulfill gaps of missing data.
		 *                     It's unique for each gap.
		 */
		$average_distance = $points_distance ? array_sum($points_distance) / count($points_distance) : 0;
		$threshold = $points_distance ? $average_distance * 3 : 0;

		// Add missing values.
		$prev_clock = null;
		$missing_points = [];
		foreach ($points as $clock => $point) {
			if ($prev_clock !== null && ($clock - $prev_clock) > $threshold) {
				$gap_interval = floor(($clock - $prev_clock) / $threshold);

				if ($missingdatafunc == SVG_GRAPH_MISSING_DATA_NONE) {
					$missing_points[$prev_clock + $gap_interval] = null;
				}
				elseif ($missingdatafunc == SVG_GRAPH_MISSING_DATA_TREAT_AS_ZERO) {
					$missing_points[$prev_clock + $gap_interval] = 0;
					$missing_points[$clock - $gap_interval] = 0;
				}
			}

			$prev_clock = $clock;
		}

		return $missing_points;
	}

	/**
	 * Add fill area to graph for metric of type SVG_GRAPH_TYPE_LINE or SVG_GRAPH_TYPE_STAIRCASE.
	 */
	protected function drawMetricArea(array $metric, array $paths) {
		$y_zero = ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) ? $this->right_y_zero : $this->left_y_zero;

		foreach ($paths as $path) {
			if (count($path) > 1) {
				$this->addItem(new CSvgGraphArea($path, $metric, $y_zero));
			}
		}
	}

	/**
	 * Add line paths to graph for metric of type SVG_GRAPH_TYPE_LINE or SVG_GRAPH_TYPE_STAIRCASE.
	 */
	protected function drawMetricsLine() {
		foreach ($this->metrics as $index => $metric) {
			if (array_key_exists($index, $this->paths) && ($metric['options']['type'] == SVG_GRAPH_TYPE_LINE
					|| $metric['options']['type'] == SVG_GRAPH_TYPE_STAIRCASE)) {
				if ($metric['options']['fill'] > 0) {
					$this->drawMetricArea($metric, $this->paths[$index]);
				}

				$this->addItem(new CSvgGraphLineGroup($this->paths[$index], $metric));
			}
		}
	}

	/**
	 * Add metric of type points to graph.
	 */
	protected function drawMetricsPoint() {
		foreach ($this->metrics as $index => $metric) {
			if ($metric['options']['type'] == SVG_GRAPH_TYPE_POINTS && array_key_exists($index, $this->paths)) {
				$this->addItem(new CSvgGraphPoints(reset($this->paths[$index]), $metric));
			}
		}
	}

	/**
	 * Add problems tooltip data to graph.
	 */
	protected function drawProblems() {
		$today = strtotime('today');
		$container = (new CSvgGroup())->addClass(CSvgTag::ZBX_STYLE_GRAPH_PROBLEMS);

		foreach ($this->problems as $problem) {
			// If problem is never recovered, it will be drown till the end of graph or till current time.
			$time_to =  ($problem['r_clock'] == 0)
				? min($this->time_till, time())
				: min($this->time_till, $problem['r_clock']);
			$time_range = $this->time_till - $this->time_from;
			$x1 = $this->canvas_x + $this->canvas_width
				- $this->canvas_width * ($this->time_till - $problem['clock']) / $time_range;
			$x2 = $this->canvas_x + $this->canvas_width
				- $this->canvas_width * ($this->time_till - $time_to) / $time_range;

			if ($this->canvas_x > $x1) {
				$x1 = $this->canvas_x;
			}

			// Make problem info.
			if ($problem['r_clock'] != 0) {
				$status_str = _('RESOLVED');
				$status_color = ZBX_STYLE_OK_UNACK_FG;
			}
			else {
				$status_str = _('PROBLEM');
				$status_color = ZBX_STYLE_PROBLEM_UNACK_FG;

				foreach ($problem['acknowledges'] as $acknowledge) {
					if ($acknowledge['action'] & ZBX_PROBLEM_UPDATE_CLOSE) {
						$status_str = _('CLOSING');
						$status_color = ZBX_STYLE_OK_UNACK_FG;
						break;
					}
				}
			}

			$clock_fmt = ($problem['clock'] >= $today)
				? zbx_date2str(TIME_FORMAT_SECONDS, $problem['clock'])
				: zbx_date2str(DATE_TIME_FORMAT_SECONDS, $problem['clock']);

			if ($problem['r_clock'] != 0) {
				$r_clock_fmt = ($problem['r_clock'] >= $today)
					? zbx_date2str(TIME_FORMAT_SECONDS, $problem['r_clock'])
					: zbx_date2str(DATE_TIME_FORMAT_SECONDS, $problem['r_clock']);
			}
			else {
				$r_clock_fmt = '';
			}

			$info = [
				'name' => $problem['name'],
				'clock' => $clock_fmt,
				'r_clock' => $r_clock_fmt,
				'url' => (new CUrl('tr_events.php'))
					->setArgument('triggerid', $problem['objectid'])
					->setArgument('eventid', $problem['eventid'])
					->getUrl(),
				'r_eventid' => $problem['r_eventid'],
				'severity' => getSeverityStyle($problem['severity'], $problem['r_clock'] == 0),
				'status' => $status_str,
				'status_color' => $status_color
			];

			// At least 3 pixels expected to be occupied to show the range. Show simple anotation otherwise.
			$draw_type = ($x2 - $x1) > 2 ? CSvgGraphAnnotation::TYPE_RANGE : CSvgGraphAnnotation::TYPE_SIMPLE;

			// Draw border lines. Make them dashed if beginning or ending of highlighted zone is visible in graph.
			if ($problem['clock'] > $this->time_from) {
				$draw_type |= CSvgGraphAnnotation::DASH_LINE_START;
			}

			if ($this->time_till > $time_to) {
				$draw_type |= CSvgGraphAnnotation::DASH_LINE_END;
			}

			$container->addItem(
				(new CSvgGraphAnnotation($draw_type))
					->setInformation(CJs::encodeJson($info))
					->setSize(min($x2 - $x1, $this->canvas_width), $this->canvas_height)
					->setPosition(max($x1, $this->canvas_x), $this->canvas_y)
					->setColor($this->color_annotation)
			);
		}

		$this->addItem($container);
	}
}
