<?php

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

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

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

class TvBinScreen extends AbstractPreloadedRegularScreen
	implements UserInputHandler
{
	const ID = 'tv_recycle_bin';

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

	public static function get_media_url_str()
	{
		return MediaURL::encode(
			array(
				'screen_id' => self::ID));
	}

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

	private $plugin;

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

	protected function do_get_folder_views(&$plugin_cookies)
	{
		$views = $this->plugin->channels_screen->get_tv_channels_folder_views($plugin_cookies);
		$views[0][PluginRegularFolderView::view_params][FolderViewParams::background_path] = 'plugin_file://img/bg/main_screen_bin_list.png';
		$views[1][PluginRegularFolderView::view_params][FolderViewParams::background_path] = 'plugin_file://img/bg/main_screen_bin_list.png';
		$views[1][PluginRegularFolderView::view_params][FolderViewParams::item_detailed_info_rel_y] = 410;

		return $views;
	}

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

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

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$actions = array();
		$dummy = UserInputHandlerRegistry::create_action($this, GUI_EVENT_TIMER);

		if (count($this->plugin->tv->get_exclude_channel_ids()) <= 0)
			return
				array_merge(
					$actions,
					array
					(
						GUI_EVENT_KEY_SETUP => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_SETUP),
						GUI_EVENT_KEY_CLEAR => $dummy,
						GUI_EVENT_KEY_MODE => $dummy,
					));

		$restore_all_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_B_GREEN);
		$restore_all_action['caption'] = 'Очистить (восстановить все)';

		$actions =
			array_merge(
				$actions,
				array
				(
					GUI_EVENT_KEY_B_GREEN => $restore_all_action,
					GUI_EVENT_KEY_POPUP_MENU => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_POPUP_MENU),
					GUI_EVENT_KEY_SETUP => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_SETUP),
					GUI_EVENT_KEY_MODE => $dummy,
				));

		return $actions;
	}

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

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

		$control_id = $user_input->control_id;
		$exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();
		$sel_ndx = 0;

		switch ($control_id)
		{
			case GUI_EVENT_TIMER:
				return null;

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

			case GUI_EVENT_KEY_POPUP_MENU:
				if (!isset($user_input->selected_media_url))
					return null;

				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Восстановить канал',
						GuiMenuItemDef::icon_url => 'plugin_file://img/restore.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'restore_channel'),
					);
				$popup_menu_items[] = array(GuiMenuItemDef::is_separator => true);
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Очистить корзину (восстановить все)',
						GuiMenuItemDef::icon_url => 'plugin_file://img/trash_can.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_B_GREEN),
					);

				return
					ActionFactorySafe::show_popup_menu($popup_menu_items);

			case 'pin_field':
				if ($this->plugin->tv->parental_passed = (md5(DuneSystem::$properties['plugin_name'] . $user_input->pin_field) === $this->plugin->tv->parental->pin))
					return
						ActionFactorySafe::close_dialog_and_run(UserInputHandlerRegistry::create_action($this, $last_action));

				return
					ActionFactorySafe::close_dialog();

			case 'input_pin_dialog_press_key_return':
				return
					ActionFactorySafe::close_dialog();

			case 'restore_channel':
				if (!isset($user_input->selected_media_url))
					return null;

				if (($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->tv->parental_passed)
				{
					$last_action = 'restore_channel';

					return
						$this->plugin->tv->get_input_pin_dialog_action($this);
				}

				$selected_media_url = MediaURL::decode($user_input->selected_media_url);
				$key = array_search($selected_media_url->channel_id, $exclude_channel_ids);

				if ($key !== false)
					unset($exclude_channel_ids[$key]);

				$num_items = count($exclude_channel_ids);
				$sel_ndx = $user_input->sel_ndx - 1;

				if ($sel_ndx < 0)
					$sel_ndx = 0;

				if ($sel_ndx >= $num_items)
					$sel_ndx = $num_items - 1;

				$this->plugin->tv->set_exclude_channel_ids($exclude_channel_ids);
				break;

			case GUI_EVENT_KEY_B_GREEN:
				if (($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->tv->parental_passed)
				{
					$last_action = GUI_EVENT_KEY_B_GREEN;

					return
						$this->plugin->tv->get_input_pin_dialog_action($this);
				}

				$exclude_channel_ids = array();
				$this->plugin->tv->set_exclude_channel_ids($exclude_channel_ids);
		}

		$range = self::create_regular_folder_range($this->get_all_folder_items(MediaURL::decode($user_input->parent_media_url), $plugin_cookies));
		$post_action = ActionFactorySafe::close_and_run(ActionFactorySafe::open_folder($user_input->parent_media_url, null, null, null, ActionFactorySafe::update_regular_folder($range, true, $sel_ndx)));

		if (NEWGUI_FEAUTURES_AVAILABLE)
		{
			EpfsHandler::update_tv_epfs($plugin_cookies);

			return
				EpfsHandler::invalidate_folders(array(TvGroupsScreen::get_media_url_str()), $post_action);
		}
		return
			ActionFactorySafe::invalidate_folders(array(TvGroupsScreen::get_media_url_str()), $post_action);
	}

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

	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
		$items = array();
		$left_margin = ControlFactoryExt::get_left_margin_str(12);
		$this->plugin->tv->folder_entered($media_url, $plugin_cookies);
		$exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();

		foreach ($exclude_channel_ids as $key => $channel_id)
		{
			if (is_null($channel = $this->plugin->tv->channels->get($channel_id)))
			{
				hd_print("Warning: channel '$cid' not found.");
				continue;
			}

			$this->plugin->user_data->select($channel_id);
			$title = $this->plugin->user_data->title;
			$title = empty($title)? $channel->get_title() : $title;
			$icon_url = $channel->get_icon_url();
			$groups = '';

			foreach ($channel->get_groups() as $group_id)
			{
				$group = $this->plugin->tv->get_group($group_id);
				$groups .= $group['title'] . '|||';
			}

			$groups = str_replace('|||', '                                               ', rtrim($groups, '|||'));
			$num_length = strlen($channel->get_number());

			$items[] =
				array
				(
					PluginRegularFolderItem::media_url =>
						MediaURL::encode
						(
							array
							(
								'channel_id' => $channel_id,
								'group_id' => HomeTv::BIN_CHANNELS_GROUP_ID,
							)
						),
					PluginRegularFolderItem::caption => $channel->get_number() . $left_margin . $title,
					PluginRegularFolderItem::view_item_params =>
						array
						(
							FolderViewItemParams::item_caption_dx => (($num_length > 2)? 40 : (($num_length > 1)? 60 : 83)) - 2,
							FolderViewItemParams::icon_path => $icon_url,
							FolderViewItemParams::item_detailed_icon_path => $icon_url,
							FolderViewItemParams::item_detailed_info => "|| | | ||Название:|$title||Категории:|$groups",
						),
				);
		}

		if (empty($items))
		{
			$items[] =
				array
				(
					PluginRegularFolderItem::media_url => 'empty',
					PluginRegularFolderItem::caption => '(пусто)',
					PluginRegularFolderItem::view_item_params =>
						array
						(
							FolderViewItemParams::item_caption_color => DEF_LABEL_TEXT_COLOR_GAINSBORO,
							FolderViewItemParams::item_detailed_info => '||',
						),
				);
		}

		return $items;
	}

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

	public function get_folder_view(MediaURL $media_url, &$plugin_cookies)
	{
		$this->ensure_folder_views($plugin_cookies);

		$idx = $this->get_folder_view_index($plugin_cookies);
		$folder_view = $this->folder_views[$idx];
		$folder_view[PluginRegularFolderView::initial_range] = $this->get_folder_range($media_url, 0, $plugin_cookies);
		$folder_media_url = MediaURL::decode($folder_view[PluginRegularFolderView::initial_range][PluginRegularFolderRange::items][0][PluginRegularFolderItem::media_url]);
		$folder_view[PluginRegularFolderView::actions] = $this->get_action_map($folder_media_url, $plugin_cookies);
		$folder_view[PluginFolderView::data][PluginRegularFolderView::view_params][FolderViewParams::extra_content_objects] = 'label{x=1330}{y=-52}{color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '}{text=Экспертный режим}';

		if (isset($folder_media_url->screen_id) && ($folder_media_url->screen_id == 'empty'))
			$folder_view[PluginRegularFolderView::view_params][ViewParams::paint_icon_selection_box] = false;

		$result =
			array
			(
				PluginFolderView::multiple_views_supported  => (count($this->folder_views) > 1 ? 1 : 0),
				PluginFolderView::archive                   => is_null($archive = $this->get_archive($media_url, $plugin_cookies)) ? null : $archive->get_archive_def(),
				PluginFolderView::view_kind                 => PLUGIN_FOLDER_VIEW_REGULAR,
				PluginFolderView::data                      => $folder_view
			);

		return $result;
	}
}

?>
