<?php

class ShortMovie
{
	public $id;
	public $name;
	public $poster_url;

	public function __construct($id, $name, $poster_url)
	{
		if (is_null($id))
			throw new Exception("ShortMovie::id is null");

		$this->id = strval($id);
		$this->name = strval($name);
		$this->poster_url = strval($poster_url);
	}
}

class ShortMovieRange
{
	public $from_ndx;
	public $total;
	public $short_movies;

	public function __construct($from_ndx, $total, $short_movies = null)
	{
		$this->from_ndx = intval($from_ndx);
		$this->total = intval($total);
		$this->short_movies = $short_movies === null ?
			array() : $short_movies;
	}
}

class MovieSeries
{
	public $id;
	public function __construct($id)
	{
		if (is_null($id))
			hd_print("MovieSeries::id is null");
		$this->id = strval($id);
	}
	public $name = '';
	public $img = '';
	public $playback_url = '';
	public $playback_url_is_stream_url = true;
	public $season_id = null;
}

class MovieSeason
{
	public $id;
	public function __construct($id)
	{
		if (is_null($id))
			hd_print("MovieSeason::id is null");
		$this->id = strval($id);
	}
	public $name = '';
	public $season_url = '';
	public $type = '';
}

class Movie implements UserInputHandler
{
	public $id;
	public $name = '';
	public $name_original = '';
	public $description = '';
	public $poster_url = '';
	public $length_min = -1;
	public $year = 0;
	public $directors_str = '';
	public $scenarios_str = '';
	public $actors_str = '';
	public $genres_str = '';
	public $rate_imdb = '';
	public $rate_kinopoisk = '';
	public $rate_mpaa = '';
	public $rate_details;
	public $country = '';
	public $budget = '';
	public $series_list = null;
	public $details;
	public $other;
	const ID = 'smart_movie';


	public function __construct($id)
	{
		if (is_null($id))
			hd_print("Movie::id is null");
		$this->id = strval($id);
	}

	public function get_handler_id()
	{ return self::ID; }


/////////////////////////////////////////////////////////////////////////////////////////

protected function get_movie_actions()
{
	UserInputHandlerRegistry::get_instance()->register_handler($this);
	$actions[GUI_EVENT_PLAYBACK_STOP] = UserInputHandlerRegistry::create_action($this, 'watched');
	$actions[GUI_EVENT_TIMER] = UserInputHandlerRegistry::create_action($this, 'timer');
	$actions[GUI_EVENT_KEY_D_BLUE] = UserInputHandlerRegistry::create_action($this, 'do_show_custom_clock_banner');
	return $actions;
}

public function handle_user_input(&$user_input, &$plugin_cookies)
{
	static $show_custom_clock_banner = true;
	static $show_custom_clock_banner2 = false;
	$time = time();
	$custom_clock_pos = array(1600, 30);
	if ($user_input->control_id == 'watched')
	{
		if ((isset($this->playback_info))&&($this->playback_info != null))
		{
			$series = $this->series_list[$this->playback_info_ndx];
				if ($series->season_id == true)
				{
					$save_folder = HD::get_items('save_folder');
						if (isset($save_folder[$user_input->plugin_vod_id][$series->season_id]))
						{
							$save_folder[$user_input->plugin_vod_id][$series->season_id][] = $series->id;
							HD::save_items('save_folder', $save_folder);
						}
				}
				if (!preg_match("/\.(?:mp3|wav|og(?:g|a)|flac|midi?|rm|m4a|aac|wma|mka|ape|jpg|png)$/i",$series->id))
				{
					$viewed_items = HD::get_items('viewed_items');
					$viewed_items[$series->id] = $this->playback_info;
					HD::save_items('viewed_items', $viewed_items);
				}
				if (isset($user_input->playback_stop_pressed))
				{
					$history_items = HD::get_items('history_items');
					$history_items = array_reverse($history_items, true);
					$history_items[$user_input->plugin_vod_id] = array('name' => $this->name,'poster_url' => $this->poster_url, 'info' => $this->name."|$series->name||Просмотрено:|".date("d.m.Y"));
					$history_items = array_reverse($history_items, true);
					if (count($history_items) == 31)
						array_pop($history_items);
					HD::save_items('history_items', $history_items);
						if ($series->season_id == true)
							return ActionFactory::invalidate_folders(array(VodSeriesListScreen::get_media_url_str($user_input->plugin_vod_id,$series->season_id)), null );
						else
							return ActionFactory::invalidate_folders(array(VodSeriesListScreen::get_media_url_str($user_input->plugin_vod_id)), null );
				}
		}
	}

	if ($user_input->control_id == 'timer')
		{
		$actions = $this->get_movie_actions();
		$post_action = null;
		$ext_command = file_get_contents('/tmp/run/ext_command.state');
		if ((preg_match('/playback_position = (\d*)/', $ext_command, $match))&&(preg_match('/playback_duration = (\d*)/', $ext_command, $matches)))
			if ((intval($match[1])>0)&&(intval($matches[1])>0))
				$this->playback_info = array ($match[1],$matches[1]);
			$this->playback_info_ndx = $user_input->plugin_vod_series_ndx;
		ActionFactory::change_behaviour($actions, 5000, $post_action);

		if ($show_custom_clock_banner2 == true)
		{
			$show_custom_clock_banner = false;
			OSDComponentFactory::add_content_box($comps, $custom_clock_pos[0], $custom_clock_pos[1], 226, 78);
			ActionFactorySafe::add_osd_image($comps, "plugin_file://icons/clock.png", $custom_clock_pos[0] + 20, $custom_clock_pos[1] + 18);
			ActionFactorySafe::add_osd_text($comps, strftime('%H:%M', $time + LOCAL_TZ_OFFSET), $custom_clock_pos[0] + 80, $custom_clock_pos[1] + 13);
		}
		if (!isset($comps)) $comps = array();
		return ActionFactorySafe::update_osd($comps, ActionFactorySafe::change_behaviour($actions, 1000));
	}

///////////////////////
	if ($user_input->control_id == 'do_show_custom_clock_banner')
	{
		if ($show_custom_clock_banner == true)
		{
			$show_custom_clock_banner = false;
			$show_custom_clock_banner2 = true;
			if (!isset($comps)) $comps = array();
			OSDComponentFactory::add_content_box($comps, $custom_clock_pos[0], $custom_clock_pos[1], 226, 78);
			ActionFactorySafe::add_osd_image($comps, "plugin_file://icons/clock.png", $custom_clock_pos[0] + 20, $custom_clock_pos[1] + 18);
			ActionFactorySafe::add_osd_text($comps, strftime('%H:%M', $time + LOCAL_TZ_OFFSET), $custom_clock_pos[0] + 80, $custom_clock_pos[1] + 13);
			$actions = $this->get_movie_actions();
			return ActionFactorySafe::update_osd($comps, ActionFactorySafe::change_behaviour($actions, 1000));
		}
		else
		{
			$show_custom_clock_banner = true;
			$show_custom_clock_banner2 = false;
			$actions = $this->get_movie_actions();
				return ActionFactorySafe::update_osd(null, ActionFactorySafe::change_behaviour($actions, 1000));
		}
	}
return null;
}

	private function to_string($v)
	{
		return $v === null ? '' : strval($v);
	}

	private function to_int($v, $default_value)
	{
		$v = strval($v);
		if (!is_numeric($v))
			return $default_value;
		$v = intval($v);
		return $v <= 0 ? $default_value : $v;
	}

		public function set_data(
		$name,
		$name_original,
		$description,
		$poster_url,
		$length_min,
		$year,
		$directors_str,
		$scenarios_str,
		$actors_str,
		$genres_str,
		$rate_imdb,
		$rate_kinopoisk,
		$rate_mpaa,
		$country,
		$budget,
		$rate_details,
		$details,
		$other,
		$urls
		)
	{
		$this->name = $this->to_string($name);
		$this->name_original = $this->to_string($name_original);
		$this->description = $this->to_string($description);
		$this->poster_url = $this->to_string($poster_url);
		$this->length_min = $length_min;
		$this->year = $this->to_int($year, -1);
		$this->directors_str = $this->to_string($directors_str);
		$this->scenarios_str = $this->to_string($scenarios_str);
		$this->actors_str = $this->to_string($actors_str);
		$this->genres_str = $this->to_string($genres_str);
		$this->rate_imdb = $this->to_string($rate_imdb);
		$this->rate_kinopoisk = $this->to_string($rate_kinopoisk);
		$this->rate_mpaa = $this->to_string($rate_mpaa);
		$this->country = $this->to_string($country);
		$this->budget = $this->to_string($budget);
		$this->rate_details = $rate_details;
		$this->details = $details;
		$this->other = $other;
		$this->urls = $urls;
		$this->series_list = array();
	}

	public function add_series_data($id, $name, $playback_url, $playback_url_is_stream_url, $season_id=null)
	{
		$series = new MovieSeries($id);
		$series->name = $this->to_string($name);
		$series->playback_url = $this->to_string($playback_url);
		$series->playback_url_is_stream_url = $playback_url_is_stream_url === true;
		if ($season_id == true)
			$series->season_id = $this->to_string($season_id);
		$this->series_list[] = $series;
	}

	public function add_season_data($id, $name, $season_url, $type)
	{
		$season = new MovieSeason($id);
		$season->name = $this->to_string($name);
		//$season->season_url = $this->to_string($season_url);
		$season->season_url = $season_url;
		$season->type = $this->to_string($type);
		$this->season_list[] = $season;
	}

	public function get_movie_array()
	{
		return array(
		PluginMovie::name => $this->name,
		PluginMovie::name_original => $this->name_original,
		PluginMovie::description => $this->description,
		PluginMovie::poster_url => $this->poster_url,
		PluginMovie::length_min => $this->length_min,
		PluginMovie::year => $this->year,
		PluginMovie::directors_str => $this->directors_str,
		PluginMovie::scenarios_str => $this->scenarios_str,
		PluginMovie::actors_str => $this->actors_str,
		PluginMovie::genres_str => $this->genres_str,
		PluginMovie::rate_imdb => $this->rate_imdb,
		PluginMovie::rate_kinopoisk => $this->rate_kinopoisk,
		PluginMovie::country => $this->country,
		PluginMovie::budget => $this->budget,
		PluginMovie::details =>  $this->details,
		PluginMovie::rate_details   => $this->rate_details
		);
	}

	public function get_vod_info($sel_id, $buffering_ms)
	{
		if (!is_array($this->series_list) || 	count($this->series_list) == 0)
			hd_print('Invalid movie: series list is empty');
		$viewed_items = HD::get_items('viewed_items');
		$series_array = array();
		$initial_series_ndx = -1;
		$initial_position_ms = array();
		foreach ($this->series_list as $ndx => $series)
		{
		
//echo("series_id from movie.php............................................................." . $series->id);
		
			$tt = '';
			if (isset($viewed_items[$series->id]))
			{
				if ($viewed_items[$series->id] =='viewed')
					$tt = '[ПРОСМ] ';
				else
				{
					$tt = '[ПРОСМ ' . HD::sec_format_duration($viewed_items[$series->id][0]) . '/' . HD::sec_format_duration($viewed_items[$series->id][1]) . '] ';
					$pos = intval($viewed_items[$series->id][0]);
					if ($pos < 0)
						$pos = 0;
					if ($pos + 5 >= intval($viewed_items[$series->id][1]))
						$pos = 0;
					$initial_position_ms[$ndx] = $pos * 1000;
				}
			}
			if (!is_null($sel_id) && $series->id === $sel_id)
				$initial_series_ndx = $ndx;
			$series_array[] = array(
							PluginVodSeriesInfo::name => $tt . $series->name,
							PluginVodSeriesInfo::playback_url => $series->playback_url,
							PluginVodSeriesInfo::playback_url_is_stream_url =>$series->playback_url_is_stream_url,
							);
		}
		$ims = 0;
		if (isset($initial_position_ms[$initial_series_ndx]))
			$ims = $initial_position_ms[$initial_series_ndx];
		return array(
		PluginVodInfo::id => $this->id,
		PluginVodInfo::name => $this->name,
		PluginVodInfo::description => $this->description,
		PluginVodInfo::poster_url => $this->poster_url,
		PluginVodInfo::series => $series_array,
		PluginVodInfo::initial_series_ndx => $initial_series_ndx,
		PluginVodInfo::buffering_ms => $buffering_ms,
		PluginVodInfo::actions => $this->get_movie_actions(),
		PluginVodInfo::timer => array(GuiTimerDef::delay_ms => 5000),
		PluginVodInfo::initial_position_ms => $ims,
		);
	}
}