<?php
///////////////////////////////////////////////////////////////////////////

require_once 'lib/dune_exception.php';
require_once 'lib/rows_factory.php';
require_once 'lib/gcomps_factory.php';
require_once 'lib/gcomp_geom.php';

class TvRowsScreen extends AbstractRowsScreen
	implements UserInputHandler
{
	const ID = 'rows_epf';

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

	private	$fav_tv_group_id;
	private $fav_tv_group_name;

	protected $tv;
	protected $epg;
	protected $images_path;

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

	public function __construct(Tv &$tv, EpgEngine &$epg)
	{
		$this->tv = $tv;
		$this->epg = $epg;
		$this->images_path = dirname(__FILE__) . '/images';

		parent::__construct(self::ID);
	}

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		return
			array
			(
				GUI_EVENT_KEY_ENTER => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_ENTER),
				GUI_EVENT_KEY_B_GREEN => UserInputHandlerRegistry::create_action($this, PLUGIN_FAVORITES_OP_MOVE_UP),
				GUI_EVENT_KEY_C_YELLOW => UserInputHandlerRegistry::create_action($this, PLUGIN_FAVORITES_OP_MOVE_DOWN),
				GUI_EVENT_KEY_D_BLUE => UserInputHandlerRegistry::create_action($this, PLUGIN_FAVORITES_OP_ADD),
				GUI_EVENT_KEY_CLEAR => UserInputHandlerRegistry::create_action($this, PLUGIN_FAVORITES_OP_REMOVE),
				GUI_EVENT_KEY_POPUP_MENU => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_POPUP_MENU),
				GUI_EVENT_PLUGIN_ROWS_INFO_UPDATE => UserInputHandlerRegistry::create_action($this, GUI_EVENT_PLUGIN_ROWS_INFO_UPDATE),
			);
	}

	public function add_rows_to_pane(&$pane, $rows_before = null, $rows_after = null, $min_row_index_for_y2 = null)
	{
		if (is_array($rows_before) && is_array($pane[PluginRowsPane::rows]))
			$pane[PluginRowsPane::rows] = array_merge($rows_before, $pane[PluginRowsPane::rows]);

		if (is_array($rows_after) && is_array($pane[PluginRowsPane::rows]))
			$pane[PluginRowsPane::rows] = array_merge($pane[PluginRowsPane::rows], $rows_after);

		if (!is_null($min_row_index_for_y2))
			$pane[PluginRowsPane::min_row_index_for_y2] = $min_row_index_for_y2;
	}

	public function get_rows_pane(MediaURL $media_url, &$plugin_cookies)
	{
		if (is_null($groups = $this->epg->get_groups()))
			return null;

		$fav_channels = $this->epg->get_tv_favorites();

		foreach($groups as $group)
		{
			$items = array();

			if ($group[PluginTvGroup::id] == $this->fav_tv_group_id)
			{
				$fav_idx = 0;
				$fav_count = count($fav_channels);

				foreach($fav_channels as $channel_id)
					if (!is_null($channel = $this->epg->get_channel($channel_id)))
						RowsFactory::add_regular_item(
							$items,
							json_encode(array('group_id' => $group[PluginTvGroup::id], 'channel_id' => $channel[ExtTvChannel::id], 'fav_idx' => $fav_idx++ . "/$fav_count")),
							$channel[ExtTvChannel::icon_url],
							$channel[ExtTvChannel::caption]);
			}
			else
			{
				$fav_stickers = null;
				RowsFactory::add_regular_sticker_rect($fav_stickers, RowsItemsParams::fav_sticker_bg_color, RowsFactory::r(229 - RowsItemsParams::fav_sticker_width - 4, 0, RowsItemsParams::fav_sticker_width + 4, RowsItemsParams::fav_sticker_height + 4));
				RowsFactory::add_regular_sticker_image($fav_stickers, $this->images_path . RowsItemsParams::fav_sticker_icon_url, RowsFactory::r(229 - RowsItemsParams::fav_sticker_width - 2, 2, RowsItemsParams::fav_sticker_width, RowsItemsParams::fav_sticker_height));

				foreach($this->epg->get_channels() as $channel)
					if (in_array($group[PluginTvGroup::id], $channel[ExtTvChannel::group_ids]) !== false)
						RowsFactory::add_regular_item(
							$items,
							json_encode(array('group_id' => $group[PluginTvGroup::id], 'channel_id' => $channel[ExtTvChannel::id])),
							$channel[ExtTvChannel::icon_url],//.'00',
							$channel[ExtTvChannel::caption],
							(($group[PluginTvGroup::id] <> $this->fav_tv_group_id) && in_array($channel[ExtTvChannel::id], $fav_channels))? $fav_stickers : null);
			}

			if (!empty($items))
			{
				$row_id = $group[PluginTvGroup::id];
				$rows[] = RowsFactory::title_row($row_id, $group[PluginTvGroup::caption], $row_id, TitleRowsParams::width, TitleRowsParams::height, ($group[PluginTvGroup::id] == $this->fav_tv_group_id)? TitleRowsParams::fav_caption_color : TitleRowsParams::def_caption_color, TitleRowsParams::font_size, TitleRowsParams::left_padding, 0, 0, TitleRowsParams::fade_enabled, TitleRowsParams::fade_color, TitleRowsParams::lite_fade_color);

				for ($i = 0; $i < count($items); $i += PaneParams::max_items_in_row)
					$rows[] = RowsFactory::regular_row(
						json_encode(array('row_ndx' => intval($i / PaneParams::max_items_in_row), 'row_id' => $row_id)),
						array_slice($items, $i, PaneParams::max_items_in_row), 'common', null, $group[PluginTvGroup::caption],
						$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, UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_ENTER), RowsParams::fade_icon_mix_color, RowsParams::fade_icon_mix_alpha, RowsParams::lite_fade_icon_mix_alpha, RowsParams::fade_caption_color);
			}
		}

		if (empty($rows))
			return null;

		$pane = RowsFactory::pane(
			$rows,
			RowsFactory::focus(GCOMP_FOCUS_DEFAULT_CUT_IMAGE, GCOMP_FOCUS_DEFAULT_RECT),
			null, true, true, -1, null, null,
			1.0, 0, 0.0, -0.5, 250);

		RowsFactory::pane_set_geometry($pane,
			PaneParams::width, PaneParams::height, PaneParams::dx, PaneParams::dy,
			PaneParams::info_height, 1,//$min_row_index_for_y2,
			PaneParams::info_width,
			PaneParams::info_height,
			PaneParams::info_dx, PaneParams::info_dy,
			PaneParams::vod_width, PaneParams::vod_height);

		$def_params = RowsFactory::variable_params(
			RowsItemsParams::width, RowsItemsParams::height, 0,
			RowsItemsParams::icon_width, RowsItemsParams::icon_height, 5,
			RowsItemsParams::caption_dy, RowsItemsParams::def_caption_color, RowsItemsParams::caption_font_size);

		$icon_dx = RowsItemsParams::icon_width/RowsItemsParams::icon_height;
		$icon_width = RowsItemsParams::icon_width+12;
		$sel_params = RowsFactory::variable_params(
			RowsItemsParams::width, RowsItemsParams::height, 5,
			$icon_width, round($icon_width/$icon_dx), 0,
			RowsItemsParams::caption_dy+10, RowsItemsParams::sel_caption_color, RowsItemsParams::caption_font_size);

		$width = round((RowsItemsParams::width*7-350)/7);
		$icon_width = round((RowsItemsParams::icon_width*7-350)/7)+round((RowsItemsParams::width-RowsItemsParams::icon_width)/$icon_dx);
		$inactive_params = RowsFactory::variable_params(
			$width, round($width/(RowsItemsParams::width/RowsItemsParams::height)), 0,
			$icon_width, round($icon_width/$icon_dx), 0,
			RowsItemsParams::caption_dy, RowsItemsParams::inactive_caption_color, RowsItemsParams::caption_font_size);

		$params = RowsFactory::item_params(
			$def_params, $sel_params, $inactive_params,
			$this->images_path . RowsItemsParams::icon_loading_url,
			$this->images_path . RowsItemsParams::icon_loading_failed_url,
			null, RowsItemsParams::caption_max_num_lines, RowsItemsParams::caption_line_spacing, null, null, null, RowsFactory::margins(6, 2, 2, 2));

		RowsFactory::set_item_params_template($pane, 'common', $params);

		return $pane;
	}

	private function do_get_info_children($media_url)
	{
		$group_id = isset($media_url->group_id)? $media_url->group_id : null;
		$channel_id = isset($media_url->channel_id)? $media_url->channel_id : null;
		$fav_status = isset($media_url->fav)? $media_url->fav : false;

		if (empty($channel_id) || empty($group_id))
			return null;

		$channel = $this->tv->get_channel($channel_id);

		if (empty($channel))
			return null;

		$title_num = 1;
		$defs = array();

		///////////// Channel number & title /////////////////

		$number = $channel->get_number();
		$defs[] = GCompsFactory::label(GCompGeom::place_top_left(150, 50, 1630 - min(3, strlen($number)) * 20, 0), null, $number, 1, PaneParams::ch_num_font_color, PaneParams::ch_num_font_size, 'ch_number');
		$defs[] = GCompsFactory::label(GCompGeom::place_top_left(PaneParams::prog_item_width + 400, PaneParams::prog_item_height, 0, 0), null, $channel->get_title(), 1, PaneParams::ch_title_font_color, PaneParams::ch_title_font_size, 'ch_title');
		$y = PaneParams::prog_item_height + 40;

		///////////// start_time, end_time, genre, country, person /////////////////

		$str = '';
		$line_spacing = array('line_spacing' => 5);

		if (!is_null($epg_data = $this->epg->get_program_info($channel_id, time())))
		{
			$prog = (object) array();
			$prog->time = strftime('%H:%M', $epg_data[ExtEpgProgram::start_tm] - $this->epg->time_zone_offset) . ' - ' . strftime('%H:%M', $epg_data[ExtEpgProgram::end_tm] - $this->epg->time_zone_offset);
			$prog->year = isset($epg_data[ExtEpgProgram::year])? $epg_data[ExtEpgProgram::year] : '';
			$prog->age = preg_match('/\[(.*)\]\s*(.*)$/', $epg_data[ExtEpgProgram::main_category], $matches)? $matches[1] : '';
			$prog->genre = isset($matches[2])? $matches[2] : '';
			$prog->country = '';
			$title = preg_replace('/^[ДТХ]\/[фс]\s+/ui', '', $epg_data[ExtEpgProgram::title]);
			$fanart_url = preg_replace('/\/c400x300\//', '/c400x248/', $epg_data[ExtEpgProgram::main_icon]);

			foreach (array('time', 'genre', 'country', 'year', 'age') as $key)
			{
				$val = $prog->{$key};

				if (!empty($val))
				{
					if ($str)
						$str .= ' | ';

					$str .= $val;
				}
			}

			///////////// Program title ////////////////

			if (!empty($title))
			{
				$lines = array_slice(explode("\n", iconv('Windows-1251', 'UTF-8', wordwrap(iconv('UTF-8', 'Windows-1251', trim(preg_replace('/(!|\?)\.+\s*$/Uu', '$1', $title))), 40, "\n", true))), 0, 2);
				$prog_title = implode("\n", $lines);

				if (strlen($prog_title) < strlen($title))
					$prog_title = $title;

				$lines = min(2, count($lines));
				$geom = GCompGeom::place_top_left(PaneParams::prog_item_width + 100, PaneParams::prog_item_height, 0, $y + ($lines > 1? 20 : 0));
				$defs[] = GCompsFactory::label($geom, null, $prog_title, 2, PaneParams::prog_title_font_color, PaneParams::prog_title_font_size, 'prog_title', $line_spacing);
				$y += PaneParams::prog_item_height * $lines + ($lines > 1? 20 : 15);
				$title_num += intval($lines > 1);
			}
			else
				$title_num--;

			if ($str)
			{
				$geom = GCompGeom::place_top_left(PaneParams::prog_item_width, PaneParams::prog_item_height, 0, $y);
				$defs[] = GCompsFactory::label($geom, null, $str, 1, PaneParams::prog_item_font_color, PaneParams::prog_item_font_size);
				$y += PaneParams::prog_item_height + 3;
			}

			if (!empty($epg_data[ExtEpgProgram::sub_title]))
			{
				$geom = GCompGeom::place_top_left(PaneParams::prog_item_width, -1, 0, $y);
				$defs[] = GCompsFactory::label($geom, null, $epg_data[ExtEpgProgram::sub_title], 1, PaneParams::prog_title_font_color, PaneParams::prog_item_font_size, 'prog_sub_title', $line_spacing);
				$y2 = ($title_num > 1)? 2 : 0;
				$y += PaneParams::prog_item_height + ($y2? -8 : 2) + $y2;
			}
			else
				$y += ($title_num > 1)? 0 : 8;

			///////////// Description ////////////////

			if (!empty($epg_data[ExtEpgProgram::desc]))//$desc))
			{
				$geom = GCompGeom::place_top_left(PaneParams::prog_item_width, -1, 0, $y);
				$defs[] = GCompsFactory::label($geom, null, /*$desc*/$epg_data[ExtEpgProgram::desc], 10 - $title_num - intval(!empty($epg_data[ExtEpgProgram::sub_title])), PaneParams::prog_title_font_color, PaneParams::prog_item_font_size, 'prog_desc', $line_spacing);
				$y += PaneParams::prog_item_height;
			}
		}
		else
		{
			$channel_desc = $channel->get_desc();

			if (!empty($channel_desc))
			{
				$geom = GCompGeom::place_top_left(PaneParams::prog_item_width, -1, 0, $y);
				$defs[] = GCompsFactory::label($geom, null, $channel_desc, 13 - $title_num, PaneParams::prog_item_font_color, PaneParams::prog_item_font_size, 'ch_desc', $line_spacing);//array('line_spacing' => 6));
				$y += PaneParams::prog_item_height;
			}
		}

		$dx = 15;
		$dy_icon = 530;
		$dy_txt = $dy_icon - 4;
		$fav_channels = $this->epg->get_tv_favorites();
		$defs[] = GCompsFactory::get_rect_def(GCompGeom::place_top_left(710, 54, 0, $dy_icon - 4), null, '#9F5843A6');
		$defs[] = GCompsFactory::get_rect_def(GCompGeom::place_top_left(984, 6, 710, $dy_icon - 4 + 48), null, '#9F5843A6');
		$defs[] = GCompsFactory::get_rect_def(GCompGeom::place_top_left(6, 6, 1700, $dy_icon - 4 + 48), null, '#9F5843A6');
		$defs[] = GCompsFactory::get_rect_def(GCompGeom::place_top_left(6, 6, 1712, $dy_icon - 4 + 48), null, '#9F5843A6');
		$defs[] = GCompsFactory::get_rect_def(GCompGeom::place_top_left(6, 6, 1724, $dy_icon - 4 + 48), null, '#9F5843A6');

		if ($group_id == $this->fav_tv_group_id)
		{
			$first = ($channel_id == reset($fav_channels));
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_top_left(52, 50, $dx, $dy_icon), null, 'gui_skin://special_icons/controls_button_green.aai', false, true, null, null, null, $first? 99 : 255);
			$defs[] = GCompsFactory::label(GCompGeom::place_top_left(PaneParams::prog_item_width, -1, $dx += 52, $dy_txt), null, 'Вперед', 1, $first? '#FF808080' : '#FFE0E0E0', PaneParams::prog_item_font_size - 4);
			$dx += 104;
			$last = ($channel_id == end($fav_channels));
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_top_left(52, 50, $dx, $dy_icon), null, 'gui_skin://special_icons/controls_button_yellow.aai', 1, 0, null, null, null, $last? 99 : 255);
			$defs[] = GCompsFactory::label(GCompGeom::place_top_left(PaneParams::prog_item_width, -1, $dx += 52, $dy_txt), null, 'Назад', 1, $last? '#FF707070' : '#FFE0E0E0', PaneParams::prog_item_font_size - 4);
			$dx += 90;
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_top_left(52, 50, $dx, $dy_icon), null, 'gui_skin://special_icons/controls_button_blue.aai');
			$defs[] = GCompsFactory::label(GCompGeom::place_top_left(PaneParams::prog_item_width, -1, $dx += 52, $dy_txt), null, 'Удалить', 1, '#FFE0E0E0', PaneParams::prog_item_font_size - 4);
			$dx += 124;
		}
		else
		{
			$defs[] = GCompsFactory::get_image_def(GCompGeom::place_top_left(52, 50, $dx, $dy_icon), null, 'gui_skin://special_icons/controls_button_blue.aai');
			$defs[] = GCompsFactory::label(GCompGeom::place_top_left(PaneParams::prog_item_width, -1, $dx += 52, $dy_txt), null, $this->fav_tv_group_name, 1, '#FFE0E0E0', PaneParams::prog_item_font_size - 4);
			$dx += 174;
		}

		///////////// Enclosing panel ////////////////

		$pane_def = GCompsFactory::get_panel_def('info_pane', GCompGeom::place_top_left(1820, PaneParams::info_height - PaneParams::dx, 0, 0), null, $defs, GCOMP_OPT_PREPAINT);
		GCompsFactory::add_extra_var($pane_def, 'info_inf_dimmed', null, array('alpha' => 64));

		return
			array
			(
				'defs' => array($pane_def),
				'fanart_url' => empty($fanart_url)? '' : $fanart_url,
			);
	}

	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		if (isset($user_input->item_id))
		{
			$media_url_str = $user_input->item_id;
			$media_url = MediaURL::decode($media_url_str);
		}
		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
			return null;

		$control_id = $user_input->control_id;

		switch ($control_id)
		{
			case GUI_EVENT_TIMER:
				if (empty($this->need_update_epf_mapping_flag))
				{
					$this->need_update_epf_mapping_flag = false;
					EpfsHandler::update_tv_epfs($plugin_cookies);

					return
						EpfsHandler::invalidate_folders();
				}
				return null;

			case GUI_EVENT_PLUGIN_ROWS_INFO_UPDATE:
				if (!isset($user_input->item_id) || !isset($user_input->folder_key))
					return null;

				$info_children = $this->do_get_info_children($media_url);
				$this->epg->tv_info_set_faulty(0);

				return
					ActionFactory::update_rows_info(
						$user_input->folder_key,
						$user_input->item_id,
						$info_children['defs'],
						empty($info_children['fanart_url'])? $this->images_path . PaneParams::vod_bg_url : $info_children['fanart_url'],
						$this->images_path . PaneParams::vod_bg_url,
						$this->images_path . PaneParams::vod_mask_url,
						array("plugin_tv://" . DuneSystem::$properties['plugin_name'] . "/$media_url_str"));

			case GUI_EVENT_KEY_POPUP_MENU:
				$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 PLUGIN_FAVORITES_OP_ADD:
			case PLUGIN_FAVORITES_OP_REMOVE:
			case PLUGIN_FAVORITES_OP_MOVE_UP:
			case PLUGIN_FAVORITES_OP_MOVE_DOWN:
				if (($media_url->group_id <> $this->fav_tv_group_id) && (strpos('_' . PLUGIN_FAVORITES_OP_REMOVE . PLUGIN_FAVORITES_OP_MOVE_UP . PLUGIN_FAVORITES_OP_MOVE_DOWN, $control_id)))
					return null;

				$fav_channel_ids = $this->epg->get_tv_favorites();
				$was_favorite = (array_search($media_url->channel_id, $fav_channel_ids) !== false);

				if ($control_id == PLUGIN_FAVORITES_OP_ADD)
					$control_id = $was_favorite? PLUGIN_FAVORITES_OP_REMOVE : PLUGIN_FAVORITES_OP_ADD;

				$this->tv->change_tv_favorites($control_id, $media_url->channel_id, $plugin_cookies);
				EpfsHandler::refresh_tv_epfs($plugin_cookies);

				return
					EpfsHandler::invalidate_folders();

			case 'refresh_screen':
				EpfsHandler::update_tv_epfs($plugin_cookies);

				return
					EpfsHandler::invalidate_folders();
		}

		$tv_play_action = ActionFactorySafe::tv_play($media_url);

		if (!isset($user_input->action_origin))
			return
				ActionFactory::change_behaviour(array_merge($this->get_action_map($media_url, $plugin_cookies), array(GUI_EVENT_TIMER => UserInputHandlerRegistry::create_action($this, GUI_EVENT_TIMER))), ActionFactory::timer(100), $tv_play_action);

		EpfsHandler::update_tv_epf($plugin_cookies);

		return
			ActionFactory::close_and_run(EpfsHandler::invalidate_folders(null, $tv_play_action));
	}

	public function get_folder_view_for_epf(&$plugin_cookies)
	{
		$media_url = MediaURL::decode(self::ID);
		$this->tv->get_tv_info($media_url, $plugin_cookies);
		$this->fav_tv_group_id = $this->epg->get_tv_fav_channels_group_id();
		$this->fav_tv_group_name = $this->epg->get_tv_fav_channels_group_name();

		return
			$this->get_folder_view($media_url, $plugin_cookies);
	}
}
?>
