<?php

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

require_once 'lib/folder_view_params.php';
require_once 'lib/abstract_preloaded_regular_screen.php';

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

class TvGroupsScreen extends AbstractPreloadedRegularScreen
	implements UserInputHandler
{
	const ID = 'tv_groups';

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

	private static $instance;
	private static $browse_mode;

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

	private $plugin;
	private $need_update_epf;
	private	$folder_view_index;

	protected $groups_list;
	protected $channels_list;
	protected $selected_group_id;
	protected $selected_channel_id;

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

	public static function get_media_url_str($browse_mode = null)
	{
		if (!is_null($browse_mode))
			self::$browse_mode = $browse_mode;

		return
			MediaURL::encode(array('screen_id' => self::ID));
	}

	public static function get_regular_folder_range(MediaURL $media_url, $from_ndx, &$plugin_cookies)
	{
		return
			self::$instance->get_folder_range($media_url, $from_ndx, $plugin_cookies);
	}

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

	private function get_tv_groups_list_folder_view($cols, $rows)
	{
		return
			array
			(
				PluginRegularFolderView::async_icon_loading => false,
				PluginRegularFolderView::view_params => array
				(
					FolderViewParams::num_cols => $cols,
					FolderViewParams::num_rows => $rows,
					FolderViewParams::paint_icon_selection_box=> true,
					FolderViewParams::paint_path_box => false,
					FolderViewParams::paint_scrollbar => true,
					FolderViewParams::paint_help_line => true,
					FolderViewParams::paint_details => false,
					FolderViewParams::paint_content_box_background => false,
					FolderViewParams::background_path=> 'plugin_file://img/bg/main_screen_groups_list.png',
					FolderViewParams::background_order => 0,
					FolderViewParams::optimize_full_screen_background => true,
					FolderViewParams::sandwich_width => 245,
					FolderViewParams::sandwich_height => 140,
					FolderViewParams::sandwich_icon_upscale_enabled => true,
					FolderViewParams::sandwich_icon_keep_aspect_ratio => false
				),

				PluginRegularFolderView::base_view_item_params => array
				(
					ViewItemParams::item_paint_icon => true,
					ViewItemParams::item_layout => HALIGN_CENTER,
					ViewItemParams::icon_valign => VALIGN_CENTER,
					ViewItemParams::item_paint_caption => true,
					ViewItemParams::icon_scale_factor => 1.25,
					ViewItemParams::icon_sel_scale_factor => 1.4,
				),

				PluginRegularFolderView::not_loaded_view_item_params => array(),
				PluginRegularFolderView::timer => ActionFactorySafe::timer(1),
			);
	}

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

	protected function do_get_folder_views(&$plugin_cookies)
	{
		return
			$this->get_tv_groups_folder_views($plugin_cookies);
	}

	protected function get_folder_view_index(&$plugin_cookies)
	{
		$this->ensure_folder_views($plugin_cookies);
		$idx = 0;
		$cnt = count($this->folder_views);

		if ($idx < 0)
			$idx = 0;
		else if ($idx >= $cnt)
			$idx = $cnt - 1;

		return intval($idx);
	}

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

	public function __construct(&$plugin)
	{
		$this->plugin = $plugin;
		$this->need_update_epf = false;
		self::$instance = $this;
		self::$browse_mode = TvBrowseModeDefs::normal;
		parent::__construct(self::ID);
		DefaultDunePlugin::create_screen($this);
		UserInputHandlerRegistry::get_instance()->register_handler($this);
	}

	public function get_tv_groups_folder_views(&$plugin_cookies)
	{
		return
			array
			(
				$this->get_tv_groups_list_folder_view(5,3),
			);
	}

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$this->folder_view_index = 0;
		$actions[GUI_EVENT_KEY_PLAY] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_PLAY);
		$actions[GUI_EVENT_KEY_SELECT] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_MODE);

		if (DUNE_FIRMWARE_BN > 8)
		{
			$actions[GUI_EVENT_KEY_MODE] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_MODE);
			$actions[GUI_EVENT_TIMER] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_TIMER);
		}

		$playlist_update_action = UserInputHandlerRegistry::create_action($this, 'show_scan_opts');
		$playlist_update_action['caption'] = 'Поиск каналов';
		$actions[GUI_EVENT_KEY_B_GREEN] = $playlist_update_action;
		$show_help_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_D_BLUE);
		$show_help_action['caption'] = 'Помощь';
		$actions[GUI_EVENT_KEY_D_BLUE] = $show_help_action;
		$actions[GUI_EVENT_KEY_SETUP] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_SETUP);
		$actions[GUI_EVENT_KEY_ENTER] = ActionFactorySafe::open_folder();
		$close_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_RETURN);
		$actions[GUI_EVENT_KEY_RETURN] = $close_action;
		$actions[GUI_EVENT_KEY_STOP] = $close_action;
		$actions[GUI_EVENT_KEY_TOP_MENU] = $close_action;

		return $actions;
	}

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

	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		static	$add_params;

		$selected_media_url = MediaURL::decode($user_input->selected_media_url);
		$control_id = $user_input->control_id;

		switch ($control_id)
		{
			case GUI_EVENT_TIMER:
				$this->plugin->tv->ensure_channels_loaded($plugin_cookies);

				if ($this->plugin->tv->channels->size() == 0)
				{
					$this->need_update_epf = true;
					ControlFactoryExt::add_vgap($defs, 10);
					ControlFactoryExt::add_multiline_label($defs, null, "Список каналов пуст. Необходимо запустить процедуру поиска каналов.\n\nТакже, при необходимости, вы можете изменить регион в настройках плагина.", 5);
					ControlFactoryExt::add_vgap($defs, 40);
					ControlFactoryExt::add_close_dialog_and_apply_button($button_defs, $this->plugin->tv, array('post_action_id' => 'groups_screen_update'), 'do_show_scan_opts', 'Продолжить', 350);
					ControlFactoryExt::add_button_centered($defs, $button_defs, 1100);
					ControlFactoryExt::add_close_dialog_button($button_defs, 'Отмена', 350);
					ControlFactoryExt::add_button_centered($defs, $button_defs, 1100);
					ControlFactoryExt::add_vgap($defs, 10);

					return
						ActionFactorySafe::show_dialog('ВНИМАНИЕ!', $defs, false, 1100);
				}
				break;

			case GUI_EVENT_KEY_RETURN:
				if ($this->need_update_epf && NEWGUI_FEAUTURES_AVAILABLE)
				{
					$this->need_update_epf = false;
					EpfsHandler::update_tv_epfs($plugin_cookies);

					return
						EpfsHandler::invalidate_folders(null, ActionFactorySafe::close_and_run());
				}

				return ActionFactorySafe::close_and_run();

			case GUI_EVENT_KEY_SETUP:
				return
					ActionFactorySafe::open_folder(SettingsScreen::get_media_url_str());

			case GUI_EVENT_KEY_D_BLUE:
				ControlFactory::add_vgap($defs, 10);
				ControlFactory::add_smart_label($defs, 'Кнопка "SETUP"', (DUNE_FIRMWARE_BN < 8)? '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Недоступно на текущей прошивке</text>' : '<text>Открыть настройки плагина</text>');
				ControlFactory::add_vgap($defs, -16);
				ControlFactory::add_smart_label($defs, 'Кнопка "SELECT"', (DUNE_FIRMWARE_BN < 8)? '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Недоступно на текущей прошивке</text>' : '<text>Вкл./Выкл. экспертный режим браузера</text>');
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_vgap($gb_defs, -10);
				ControlFactory::add_label($gb_defs, '  Кнопка "INFO"', 'Посмотреть/Изменить свойства канала');
				ControlFactoryExt::add_group_box($defs, $gb_defs, 'На выделенном канале', 1200);
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_close_dialog_button($button_defs, 'OK', 350);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1200);
				ControlFactory::add_vgap($defs, 10);

				return
					ActionFactorySafe::show_dialog(
						'Помощь по управлению',
						$defs,
						true,
						1200);

			case GUI_EVENT_KEY_MODE:
				$browse_mode = (self::$browse_mode == TvBrowseModeDefs::normal)? TvBrowseModeDefs::full : TvBrowseModeDefs::normal;

				return
					ActionFactorySafe::invalidate_folders(array(self::get_media_url_str($browse_mode)));

			case GUI_EVENT_KEY_PLAY:
				if ($selected_media_url->screen_id == TvBinScreen::ID)
					return null;

				$this->plugin->epg->tv_info_set_faulty(1);

				if (($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->tv->parental_passed)
				{
					if (!isset($selected_media_url->group_id) && ($selected_media_url->screen_id == TvFavoritesScreen::ID))
						$channels = $this->plugin->tv->get_fav_channel_ids($plugin_cookies);
					else
					{
						try
						{
							$group = $this->plugin->tv->get_group($selected_media_url->group_id);
						}
						catch (Exception $e)
						{
							throw new Exception(get_class($this).": ({$this->get_handler_id()}): Group {$selected_media_url->group_id} not found.");
							return null;
						}

						$channels = $group['channels'];
					}

					if (!empty($channels))
						foreach ($channels as $channel_id)
							if (!empty($channel_id) && $this->plugin->tv->get_channel($channel_id)->is_adult())
								return
									$this->plugin->tv->get_input_pin_dialog_action($this->plugin->tv);
				}

				return
					UserInputHandlerRegistry::create_action($this->plugin->tv, 'tv_play', array('initial_media_url' => $user_input->selected_media_url));

			case 'do_show_provider_opts':
				$post_action =
					ActionFactorySafe::invalidate_folders(
						array(
							empty($this->plugin->tv->parent_media_url_str)? '' : $this->plugin->tv->parent_media_url_str,
							TvGroupsScreen::get_media_url_str(),
							TvChannelsScreen::get_active_media_url_str(),
							TvFavoritesScreen::get_active_media_url_str(),
						)
					);

				return
					$this->plugin->settings_screen->show_dialog(SettingsDialogsDefs::provider_opts, DIALOG_FRAME_STYLE_DEFAULT, $post_action);

			case 'show_scan_opts':
				$this->need_update_epf = true;

				return
					UserInputHandlerRegistry::create_action($this->plugin->tv, 'do_show_scan_opts', array('post_action_id' => 'groups_screen_update'));
		}

		return null;
	}

	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
		$items = array();
		$tv_exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();
		$this->plugin->tv->ensure_channels_loaded($plugin_cookies);

		if (self::$browse_mode == TvBrowseModeDefs::normal)
			foreach ($this->plugin->tv->groups[HomeTv::ALL_CHANNELS_GROUP_ID]['channels'] as $channel_id)
				if (is_null($live_url = $this->plugin->tv->get_tv_playback_url($channel_id, 0, RET_LIVE_TEMPLATE_URL)) ||
					(!$this->plugin->pf_enabled && preg_match('/\/mdrm\/CH_.+\/manifest\.mpd/', $live_url)))
					$tv_exclude_channel_ids[] = $channel_id;

		foreach ($this->plugin->tv->get_groups() as $group_id => $group)
		{
			//if ($group_id == HomeTv::ALL_CHANNELS_GROUP_ID)
			//	continue;

			if (($group_id <> HomeTv::FAV_CHANNELS_GROUP_ID) && (count(array_diff($group['channels'], $tv_exclude_channel_ids)) == 0))
				continue;

			if ((self::$browse_mode == TvBrowseModeDefs::full) && ($group_id == HomeTv::FAV_CHANNELS_GROUP_ID))
				continue;

			$item_idx = count($items);
			$items[] =
				array
				(
					PluginRegularFolderItem::media_url => ($group_id == HomeTv::FAV_CHANNELS_GROUP_ID)? TvFavoritesScreen::get_media_url_str(self::$browse_mode) : TvChannelsScreen::get_media_url_str($group_id, self::$browse_mode),
					PluginRegularFolderItem::caption => $group['title'],
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => $group['icon_url'],
						ViewItemParams::item_detailed_icon_path => $group['icon_url'],
					)
				);

			if ($group_id == HomeTv::FAV_CHANNELS_GROUP_ID)
				$items[$item_idx][PluginRegularFolderItem::view_item_params][ViewItemParams::item_caption_color] = DEF_LABEL_TEXT_COLOR_SKYBLUE;
		}

		if (self::$browse_mode == TvBrowseModeDefs::full)
			$this->plugin->tv->add_special_groups($items, $plugin_cookies);

		return $items;
	}

	public function get_folder_view(MediaURL $media_url, &$plugin_cookies)
	{
		$folder_view = parent::get_folder_view($media_url, $plugin_cookies);

		if (self::$browse_mode == TvBrowseModeDefs::full)
			$folder_view[PluginFolderView::data][PluginRegularFolderView::view_params][FolderViewParams::extra_content_objects] = 'label{x=1330}{y=-40}{color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '}{text=Экспертный режим}';

		return $folder_view;
	}

	public function get_next_folder_view(MediaURL $media_url, &$plugin_cookies)
	{
		$this->ensure_folder_views($plugin_cookies);
		$idx = 0;
		++$idx;

		if ($idx >= count($this->folder_views))
			$idx = 0;

		$this->plugin->tv->unload_channels();
		$this->need_update_epf = true;

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

	public function get_archive(MediaURL $media_url, &$plugin_cookies)
	{
		return
			$this->plugin->tv->get_archive($media_url, $plugin_cookies);
	}

}

///////////////////////////////////////////////////////////////////////////
?>
