<?php

class HomeTvRowsScreen extends TvRowsScreen implements UserInputHandler
{
	const PLAYBACK_HISTORY_ROW_ID = '__playback_history_row';

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

	private	$remove_playback_point;
	private	$clear_playback_points;

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

	public function __construct(Tv &$tv, EpgEngine &$epg)
	{
		$this->tv = $tv;
		$this->epg = $epg;
		parent::__construct($tv, $epg);
	}

	public function get_rows_pane(MediaURL $media_url, &$plugin_cookies)
	{
		if (is_null($pane = parent::get_rows_pane($media_url, $plugin_cookies)))
		{
			$defs = array();
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_center(200, 200, 0, -250), null, PLUGIN_IMG_PATH . '/plugin_icon.png', 1, 1);
			$defs[] = GCompsFactory::label_v2(GCompGeom::place_center(-1, -1, 0, -70), 'СПИСОК КАНАЛОВ ПУСТ!', 4, '#FFAFAFA0', 60);
			$defs[] = GCompsFactory::label_v2(GCompGeom::place_center(-1, -1, 0, 50), 'Выберите локацию, запустите поиск каналов.', 4, '#FFAFAFA0', 50);
			$defs[] = GCompsFactory::label_v2(GCompGeom::place_center(-1, -1, 0, 130), '', 4, '#FFAFAFA0', 50);
			$button_def = GCompsFactory::get_button_def('location_select', GCompGeom::place_center(400, 54, -250, 200), null, '    Выбор локации', false, true);
			GCompsFactory::set_focusable($button_def);
			$defs[] = $button_def;
			$button_def = GCompsFactory::get_button_def('channels_search', GCompGeom::place_center(400, 54, 200, 200), null, '    Поиск каналов', false, true);
			GCompsFactory::set_focusable($button_def);
			$defs[] = $button_def;
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_center(40, 40, -410, 198), null, PLUGIN_IMG_PATH . '/location_opts.png', 1, 1);
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_center(40, 40, 46, 196), null, PLUGIN_IMG_PATH . '/tv_channels.png', 1, 1);
			$rows[] = RowsFactory::gcomps_row('single_row', $defs, null, 0, 1920, 800);

			return
				RowsFactory::pane($rows);
		}

		if (class_exists('PlaybackPoints'))
		{
			$rows = array();
			$min_row_index_for_y2 = 1;

			if (empty($this->clear_playback_points))
			{
				$watched = array();

				foreach(PlaybackPoints::get_all() as $point)
				{
					$channel_id = $point->channel_id;

					if (is_null($channel = $this->epg->get_channel($channel_id)) || $channel[ExtTvChannel::is_adult])
						continue;

					$group_id = in_array($point->group_id, $channel['group_ids'])? $point->group_id : null;
					$channel_ts = ($point->archive_tm > 0)? $point->archive_tm + $point->position : ($channel[ExtTvChannel::have_archive]? $point->time : 0);

					if (isset($watched["$channel_id"]))
						continue;

					if (empty($channel_ts))
					{
						$watched["$channel_id"] =
							array
							(
								'group_id' => $group_id,
								'channel_id' => $channel_id,
								'archive_tm' => 0,
								'view_progress' => 0,
								'program_tm' => 0,
								'program_title' => $channel[ExtTvChannel::caption],
								'program_icon_url' => '',
							);
					}
					else if (!is_null($prog_info = $this->epg->get_program_info($channel_id, $channel_ts, false)))
					{
						$watched["$channel_id"] =
							array
							(
								'group_id' => $group_id,
								'channel_id' => $channel_id,
								'archive_tm' => $channel_ts,
								'view_progress' => max(0.01, min(1, 1 - round(($prog_info[ExtEpgProgram::end_tm] - $channel_ts)/($prog_info[ExtEpgProgram::end_tm] - $prog_info[ExtEpgProgram::start_tm]), 2))),
								'program_tm' => $prog_info[ExtEpgProgram::start_tm],
								'program_title' => $prog_info[ExtEpgProgram::title] . (empty($prog_info[ExtEpgProgram::sub_title])? '' : '. ' . $prog_info[ExtEpgProgram::sub_title]),
								'program_icon_url' => $prog_info[ExtEpgProgram::main_icon],
							);
					}
					else
					{
						$watched["$channel_id"] =
							array
							(
								'group_id' => $group_id,
								'channel_id' => $channel_id,
								'archive_tm' => $channel_ts,
								'view_progress' => 0,
								'program_tm' => 0,
								'program_title' => '',
								'program_icon_url' => '',
							);
					}

					if (count($watched) >= 7)
						break;
				}

				$items = array();

				foreach($watched as $item)
					if (!is_null($channel = $this->epg->get_channel($item['channel_id'])))
					{
						$id = json_encode(array('group_id' => $item['group_id'], 'channel_id' => $item['channel_id'], 'archive_tm' => $item['archive_tm'], 'program_tm' => $item['program_tm'], 'row_id' => self::PLAYBACK_HISTORY_ROW_ID));

						if (isset($this->removed_playback_point))
							if ($this->removed_playback_point == $id)
							{
								$this->removed_playback_point = null;
								PlaybackPoints::clear();
								continue;
							}

						$stickers = null;

						if (!empty($item['view_progress']) && !empty($item['program_icon_url']))
						{
							$rect = RowsFactory::r(RowsItemsParams::icon_width - RowsItemsParams::watch_sticker_icon_width, 0, RowsItemsParams::watch_sticker_icon_width, RowsItemsParams::watch_sticker_icon_height);
							RowsFactory::add_regular_sticker_rect($stickers, RowsItemsParams::watch_sticker_icon_bg_color, $rect);
							RowsFactory::add_regular_sticker_image($stickers, $channel[ExtTvChannel::icon_url], $rect);
						}

						if ($item['view_progress'] > 0)
						{
							RowsFactory::add_regular_sticker_rect($stickers, RowsItemsParams::watch_sticker_progress_bg_color, RowsFactory::r(0, RowsItemsParams::icon_height - RowsItemsParams::watch_sticker_progress_height, RowsItemsParams::icon_width, RowsItemsParams::watch_sticker_progress_height));
							RowsFactory::add_regular_sticker_rect($stickers, RowsItemsParams::watch_sticker_progress_color, RowsFactory::r(0, RowsItemsParams::icon_height - RowsItemsParams::watch_sticker_progress_height, round(RowsItemsParams::icon_width * $item['view_progress']), RowsItemsParams::watch_sticker_progress_height));
						}

						RowsFactory::add_regular_item(
							$items,
							$id,
							empty($stickers)? $channel[ExtTvChannel::icon_url] : $item['program_icon_url'],
							empty($stickers)? $channel[ExtTvChannel::caption] : $item['program_title'],
							$stickers);
					}

				if (count($items) < 7)
				{
					$t = time();
					$epf_data = EpfsHandler::get_epf();

					if (isset($epf_data->data->pane->rows))
						foreach($epf_data->data->pane->rows as $row)
							if ($row->type == PLUGIN_ROW_TYPE_REGULAR)
							{
								$row_decode_id = json_decode($row->id);

								if (!isset($row_decode_id->row_id) || ($row_decode_id->row_id <> self::PLAYBACK_HISTORY_ROW_ID))
									break;

								foreach($row->data->items as $item)
								{
									if (isset($this->removed_playback_point))
										if ($this->removed_playback_point == $item->id)
										{
											$this->removed_playback_point = null;
											PlaybackPoints::clear();
											continue;
										}

									if (is_null($media_url = json_decode($item->id)))
										continue;

									$channel_id = $media_url->channel_id;

									if (!isset($watched[$channel_id]))
										if (!is_null($channel = $this->epg->get_channel($channel_id)))
											if ($media_url->program_tm + $channel[ExtTvChannel::archive_past_sec] - 60 > $t)
											{
												$items[] = $item;
												$watched[$channel_id] = '';

												if (count($items) >= 7)
													break 2;
											}

								}

								break;
							}
				}

				if (!empty($items))
				{
					$min_row_index_for_y2 = 2;
					$row_id = self::PLAYBACK_HISTORY_ROW_ID;
					$rows[] = RowsFactory::title_row($row_id, 'Продолжить просмотр', $row_id, TitleRowsParams::width, TitleRowsParams::height, '#FFEFAA16', TitleRowsParams::font_size, TitleRowsParams::left_padding, 0, 0, TitleRowsParams::fade_enabled, TitleRowsParams::fade_color, TitleRowsParams::lite_fade_color);
					$rows[] = RowsFactory::regular_row(json_encode(array('row_ndx' => 0, 'row_id' => $row_id)), $items, 'common', null, 'Продолжить', $row_id, RowsParams::width, RowsParams::height, RowsParams::height - TitleRowsParams::height, RowsParams::left_padding, RowsParams::inactive_left_padding, RowsParams::right_padding, RowsParams::hide_captions, false, RowsParams::fade_enable, null, null, RowsParams::fade_icon_mix_color, RowsParams::fade_icon_mix_alpha, RowsParams::lite_fade_icon_mix_alpha, RowsParams::fade_caption_color);
				}
			}
			else
			{
				PlaybackPoints::clear();
				$this->clear_playback_points = false;
			}

			if (!empty($rows))
				parent::add_rows_to_pane($pane, $rows, null, $min_row_index_for_y2);
		}

		return $pane;
	}

	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		$this->removed_playback_point = null;

		if (isset($user_input->item_id))
			$media_url = MediaURL::decode($user_input->item_id);
		else if (isset($user_input->selected_row_id, $user_input->selected_item_id))
		{
			$media_url = MediaURL::decode($user_input->selected_item_id);
			$media_url->row_id = MediaURL::decode($user_input->selected_row_id)->row_id;
		}
		else if (isset($user_input->selected_row_id))
		{
			$media_url = MediaURL::decode($user_input->selected_row_id);
			$media_url->group_id = $media_url->row_id;
		}
		else
			return null;

		switch ($user_input->control_id)
		{
			case GUI_EVENT_KEY_POPUP_MENU:
				if ($media_url->row_id == self::PLAYBACK_HISTORY_ROW_ID)
				{

					$menu_items[] =
						array
						(
							GuiMenuItemDef::caption => '  Удалить',
							GuiMenuItemDef::icon_url => $this->images_path . '/remove.png',
							GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'remove_playback_point'),
						);
					$menu_items[] =
						array
						(
							GuiMenuItemDef::caption => '  Очистить',
							GuiMenuItemDef::icon_url => $this->images_path . '/brush.png',
							GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'clear_playback_points'),
						);
					$menu_items[] =
						array
						(
							GuiMenuItemDef::is_separator => true,
						);
				}

				$menu_items[] =
					array
					(
						GuiMenuItemDef::caption => '  Обновить',
						GuiMenuItemDef::icon_url => $this->images_path . '/refresh.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'refresh_screen'),
					);

				return
					ActionFactory::show_popup_menu($menu_items);

			case 'remove_playback_point':
				$this->removed_playback_point = $media_url->get_raw_string();

			case 'clear_playback_points':
				$this->clear_playback_points = empty($this->removed_playback_point);
				EpfsHandler::refresh_tv_epfs($plugin_cookies);

				return
					EpfsHandler::invalidate_folders();

			case PLUGIN_FAVORITES_OP_ADD:
			case PLUGIN_FAVORITES_OP_REMOVE:
			case PLUGIN_FAVORITES_OP_MOVE_UP:
			case PLUGIN_FAVORITES_OP_MOVE_DOWN:
				if ($media_url->row_id == self::PLAYBACK_HISTORY_ROW_ID)
					return null;

				break;

			case GUI_EVENT_KEY_ENTER:
				if (isset($user_input->selected_item_id))
				{
					hd_print('selected_item_id');
					if ($user_input->selected_item_id == 'location_select')
						return
							$this->tv->open_settings(SettingsDialogsDefs::provider_opts);
					else if ($user_input->selected_item_id == 'channels_search')
						return
							UserInputHandlerRegistry::create_action($this->tv, 'do_show_scan_opts', array('post_action_id' => GUI_EVENT_PLAYBACK_STOP, 'post_action_params' => serialize(array('playback_stop_pressed' => 0))));
				}

				$add_params =
					array
					(
						'resume_mode' => 1,
						'resume_tv_group' => $media_url->group_id,
						'resume_tv_channel' => $media_url->channel_id,
						'resume_tv_archive_tm' => isset($media_url->archive_tm)? $media_url->archive_tm : -1,
						'resume_tv_is_favorite' => ($media_url->group_id == $this->epg->tv_fav_channels_group_id),
						'dialog_frame_style' => DIALOG_FRAME_STYLE_GLASS,
					);

				return
					SplashScreen::open_and_run(UserInputHandlerRegistry::create_action($this->tv->plugin->launcher, 'plugin_entry', $add_params));
		}

		return
			parent::handle_user_input($user_input, $plugin_cookies);
	}
}
?>
