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

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

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

class TvChannelsScreen extends AbstractPreloadedRegularScreen
	implements UserInputHandler
{
	const ID = 'tv_channels';

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

	private static	$browse_mode;
	private	static	$channel_properties_ops;
	private	static	$media_url_str;

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

	private $plugin;

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

	private static function GET_TV_CHANNELS_LIST_FOLDER_VIEW()
	{
		return
			array
			(
				array
				(
					PluginRegularFolderView::async_icon_loading => false,
					PluginRegularFolderView::view_params => array
					(
						FolderViewParams::num_cols => 1,
						FolderViewParams::num_rows => 13,
						FolderViewParams::paint_icon_selection_box=> true,
						FolderViewParams::paint_details => true,
						FolderViewParams::paint_details_box_background => false,
						FolderViewParams::paint_content_box_background => false,
						FolderViewParams::paint_path_box => false,
						FolderViewParams::paint_scrollbar => true,
						FolderViewParams::paint_help_line => true,
						FolderViewParams::content_box_y => 68,
						FolderViewParams::content_box_width => 1200,
						FolderViewParams::content_box_height => 900,
						FolderViewParams::icon_badge_box_dx => -552,
						FolderViewParams::icon_badge_box_height => 60,
						FolderViewParams::icon_badge_box_width => 322,
						FolderViewParams::icon_selection_box_dx => -334,
						FolderViewParams::icon_selection_box_dy => -23,
						FolderViewParams::icon_selection_box_width => 937,
						FolderViewParams::icon_selection_box_height => 50,
						FolderViewParams::paint_icon_badge_box => true,
						FolderViewParams::background_path=> 'plugin_file://img/bg/main_screen_channels_list.png',
						FolderViewParams::background_order => 0,
						FolderViewParams::optimize_full_screen_background => true,
						FolderViewParams::zoom_detailed_icon => true,
						FolderViewParams::detailed_icon_valign => VALIGN_CENTER,
						FolderViewParams::item_detailed_info_rel_y => 280,
						FolderViewParams::item_detailed_info_auto_line_break => true,
						FolderViewParams::item_detailed_info_font_size => FONT_SIZE_SMALL,
						FolderViewParams::item_detailed_info_title_color => DEF_LABEL_TEXT_COLOR_SKYBLUE,
					),
					PluginRegularFolderView::base_view_item_params => array
					(
						FolderViewItemParams::item_paint_icon => true,
						FolderViewItemParams::item_layout => HALIGN_LEFT,
						FolderViewItemParams::icon_valign => VALIGN_CENTER,
						FolderViewItemParams::icon_width => 97,
						FolderViewItemParams::icon_height => 55,
						FolderViewItemParams::icon_keep_aspect_ratio => false,
						FolderViewItemParams::item_override_default_badge => true,
						FolderViewItemParams::item_badge_icon_path => 'plugin_file://img/channel_badge.png',
						FolderViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
					),
					PluginRegularFolderView::not_loaded_view_item_params => array(),
				),

				array
				(
					PluginRegularFolderView::async_icon_loading => false,
					PluginRegularFolderView::view_params => array
					(
						FolderViewParams::num_cols => 1,
						FolderViewParams::num_rows => 13,
						FolderViewParams::paint_icon_selection_box=> true,
						FolderViewParams::paint_details => true,
						FolderViewParams::paint_details_box_background => false,
						FolderViewParams::paint_content_box_background => false,
						FolderViewParams::paint_path_box => false,
						FolderViewParams::paint_widget => true,
						FolderViewParams::paint_scrollbar => true,
						FolderViewParams::paint_help_line => true,
						FolderViewParams::content_box_y => 68,
						FolderViewParams::content_box_width => 1200,
						FolderViewParams::content_box_height => 900,
						FolderViewParams::icon_badge_box_dx => -552,
						FolderViewParams::icon_badge_box_height => 60,
						FolderViewParams::icon_badge_box_width => 322,
						FolderViewParams::icon_selection_box_dx => -334,
						FolderViewParams::icon_selection_box_dy => -23,
						FolderViewParams::icon_selection_box_width => 937,
						FolderViewParams::icon_selection_box_height => 50,
						FolderViewParams::paint_icon_badge_box => true,
						FolderViewParams::background_path=> 'plugin_file://img/bg/main_screen_channels_list.png',
						FolderViewParams::background_order => 0,
						FolderViewParams::optimize_full_screen_background => true,
						FolderViewParams::zoom_detailed_icon => true,
						FolderViewParams::detailed_icon_valign => VALIGN_BOTTOM,
						FolderViewParams::item_detailed_info_rel_y => 392,
						FolderViewParams::item_detailed_info_auto_line_break => true,
						FolderViewParams::item_detailed_info_font_size => FONT_SIZE_SMALL,
						FolderViewParams::item_detailed_info_title_color => DEF_LABEL_TEXT_COLOR_SKYBLUE,
					),
					PluginRegularFolderView::base_view_item_params => array
					(
						FolderViewItemParams::item_paint_icon => true,
						FolderViewItemParams::item_layout => HALIGN_LEFT,
						FolderViewItemParams::icon_valign => VALIGN_CENTER,
						FolderViewItemParams::icon_width => 97,
						FolderViewItemParams::icon_height => 55,
						FolderViewItemParams::icon_keep_aspect_ratio => false,
						FolderViewItemParams::item_override_default_badge => true,
						FolderViewItemParams::item_badge_icon_path => 'plugin_file://img/channel_badge.png',
						FolderViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
					),
					PluginRegularFolderView::not_loaded_view_item_params => array(),
				),
			);
	}

	public static function get_media_url_str($group_id, $browse_mode = null)
	{
		self::$browse_mode = empty($browse_mode)? TvBrowseModeDefs::normal : $browse_mode;

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

	public static function get_active_media_url_str()
	{
		return
			empty(self::$media_url_str)? '' : self::$media_url_str;
	}

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

	private function get_group_list()
	{
		$result = array();

		foreach ($this->plugin->tv->get_groups() as $group_id => $group)
			$result[$group_id] = $group['title'];

		return $result;
	}

	private function get_multiple_edit_dialog_controls_defs(&$add_params)
	{
		ControlFactory::add_vgap($defs, -10);

		switch ($add_params['phase'])
		{
			case 0:
				ControlFactory::add_multiline_label($defs, null, 'Чтобы применить одинаковые свойства для группы каналов, выберите значения для нужных свойств и нажмите "Продолжить":', 3);

				foreach ($add_params as $param => $value)
				{
					if (($param == 'phase') || (($param == 'deint_combo_id') && (get_platform_kind() == 'android')))
						continue;

					ControlFactory::add_combobox($defs, $this, $add_params,
						preg_replace('/_id$/', '', $param),
						self::$channel_properties_ops[$param]['caption'],
						$value,
						self::$channel_properties_ops[$param]['actions'],
						1300,
						true);
					ControlFactory::add_vgap($defs, -10);
				}

				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_button($button_defs, $this, null, 'multiple_edit_continue', null, 'Продолжить', 400);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1300);
				break;

			case 1:
				ControlFactory::add_label($defs, null, 'Выбраны следующие свойства и действия:');

				foreach ($add_params as $param => $value)
				{
					if (($param == 'phase') || ($param == 'groups_combo_id'))
						continue;

					ControlFactory::add_vgap($defs, -24);
					ControlFactory::add_multiline_label($defs, self::$channel_properties_ops[$param]['caption'] . ':', ((($param == 'epg_timeshift_combo_id') || ($param == 'zoom_combo_id') || ($param == 'deint_combo_id'))? 'Применить значение "' . self::$channel_properties_ops[$param]['actions'][$value] . '"' : self::$channel_properties_ops[$param]['actions'][$value]), 2);
				}

				ControlFactory::add_multiline_label($defs, null, 'Выберите группу каналов для которых будут применены указанные действия.', 2);
				ControlFactory::add_vgap($defs, -5);
				ControlFactory::add_combobox($defs, $this, null,
					'groups_combo',
					'Группа каналов:',
					$add_params['groups_combo_id'],
					$this->get_group_list(),
					1300,
					true);
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_button($button_defs, $this, null, 'multiple_edit_apply', null, 'Применить', 400);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1300);
				break;

			case 2:
				ControlFactory::add_smart_label($defs, null, '<gap width=110/><text>Ни одно свойство не выбрано, продолжение не возможно!</text>');
				ControlFactory::add_vgap($defs, 20);
				break;

			case 3:
				if (empty($add_params['ch_count']))
				{
					$group = $this->plugin->tv->get_group($add_params['groups_combo_id']);
					ControlFactory::add_multiline_label($defs, null, "Операция была прервана!\nОтсутствуют каналы в группе \"{$group['title']}\".", 2);
				}
				else
					ControlFactory::add_label($defs, null, "Операция выполнена успешно! Обработано каналов: {$add_params['ch_count']}");

				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'update_parent_folders', 'Закрыть', 400);
				break;
		}

		if ($add_params['phase'] <= 2)
			ControlFactory::add_close_dialog_button($button_defs, ($add_params['phase'] > 1)? 'Ok' : 'Отмена', 400);

		ControlFactoryExt::add_button_centered($defs, $button_defs, 1300);
		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

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

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

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

	public function __construct(&$plugin)
	{
		parent::__construct(self::ID);
		$this->plugin = $plugin;

		self::$channel_properties_ops =
			array
			(
				'title_combo_id' =>
					array
					(
						'caption' => 'Название канала',
						'actions' =>
							array
							(
								'ignore' => 'Игнорировать это свойство',
								'' => 'Применить значение по умолчанию',
							),
					),
				'icon_url_combo_id' =>
					array
					(
						'caption' => 'Иконка (URL)',
						'actions' =>
							array
							(
								'ignore' => 'Игнорировать это свойство',
								'' => 'Применить значение по умолчанию',
							),
					),
				'subchannel_combo_id' =>
					array
					(
						'caption' => 'Субканал',
						'actions' =>
							array
							(
								'ignore' => 'Игнорировать это свойство',
								'' => 'Применить значение "Автоподбор"',
							),
					),
				'epg_id_combo_id' =>
					array
					(
						'caption' => 'Телегид (ID)',
						'actions' =>
							array
							(
								'ignore' => 'Игнорировать это свойство',
								'empty' => 'Деактивировать телегид',
								'' => 'Применить значение "Автоподбор"',
							),
					),
				'live_url_combo_id' =>
					array
					(
						'caption' => 'Прямой эфир (URL)',
						'actions' =>
							array
							(
								'ignore' => 'Игнорировать это свойство',
								'' => 'Применить значение "Автоподбор"',
							),
					),
				'tv_archive_url_combo_id' =>
					array
					(
						'caption' => 'ТВ архив (URL)',
						'actions' =>
							array
							(
								'ignore' => 'Игнорировать это свойство',
								'' => 'Применить значение "Автоподбор"',
							),
					),
				'epg_timeshift_combo_id' =>
					array
					(
						'caption' => 'Сдвиг телепрограммы',
						'actions' =>
							array('ignore' => 'Игнорировать это свойство') + $this->plugin->channels_editor->get_epg_timeshift_ops(),
					),
				'zoom_combo_id' =>
					array
					(
						'caption' => 'Масштабирование',
						'actions' => array('ignore' => 'Игнорировать это свойство') + $this->plugin->channels_editor->get_zoom_presets_ops(),
					),
				'deint_combo_id' =>
					array
					(
						'caption' => 'Сглаживание',
						'actions' => array('ignore' => 'Игнорировать это свойство') + $this->plugin->channels_editor->get_deinterlacing_modes_ops(),
					),
			);

		DefaultDunePlugin::create_screen($this);
		UserInputHandlerRegistry::get_instance()->register_handler($this);
	}

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

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

	public function get_tv_channels_folder_views(&$plugin_cookies)
	{
		$fw = get_parsed_firmware_ver();
		$folder_views = self::GET_TV_CHANNELS_LIST_FOLDER_VIEW();

		return
			($fw['branch_num'] < 10)? array($folder_views[0]) : $folder_views;
	}

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$actions[GUI_EVENT_KEY_MODE] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_MODE);
		$actions[GUI_EVENT_KEY_SETUP] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_SETUP);

		if (isset($media_url->screen_id) && ($media_url->screen_id == 'empty'))
			return $actions;

		if ($this->plugin->tv->favorites_enabled)
		{
			$add_favorite_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_D_BLUE);
			$add_favorite_action['caption'] = 'Избранное';
			$actions[GUI_EVENT_KEY_D_BLUE] = $add_favorite_action;
		}

		$popup_menu_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_POPUP_MENU);
		$popup_menu_action['caption'] = 'Меню';
		$tv_play_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_PLAY);
		$show_sorter_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_B_GREEN);
		$show_sorter_action['caption'] = 'Сортировка';
		$actions[GUI_EVENT_KEY_POPUP_MENU] = $popup_menu_action;
		$actions[GUI_EVENT_KEY_B_GREEN] = $show_sorter_action;
		$actions[GUI_EVENT_KEY_ENTER] = $tv_play_action;
		$actions[GUI_EVENT_KEY_PLAY] = $tv_play_action;
		$actions[GUI_EVENT_KEY_INFO] = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_INFO);

		return $actions;
	}

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

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

		$selected_media_url = MediaURL::decode($user_input->selected_media_url);
		$is_radio_point = !empty($selected_media_url->is_radio_point);
		$channel_id = $selected_media_url->channel_id;
		$tv_fav_channel_ids = $this->plugin->tv->get_fav_channel_ids($plugin_cookies, true);
		$is_favorite = (strpos($tv_fav_channel_ids, $channel_id) !== false);
		$sel_ndx = $user_input->sel_ndx;

		switch ($user_input->control_id)
		{
			case GUI_EVENT_KEY_SETUP:
				return
					ActionFactorySafe::open_folder(SettingsScreen::get_media_url_str());

			case GUI_EVENT_KEY_MODE:
				$parent_media_url = MediaURL::decode($user_input->parent_media_url);
				$browse_mode = (self::$browse_mode == TvBrowseModeDefs::normal)? TvBrowseModeDefs::full : TvBrowseModeDefs::normal;

				return
					ActionFactorySafe::invalidate_folders(array(self::get_media_url_str($selected_media_url->group_id, $browse_mode), TvGroupsScreen::get_media_url_str($browse_mode)));

			case GUI_EVENT_KEY_PLAY:
				$plugin_cookies_playback_udp = json_decode($plugin_cookies->playback_udp);

				if ($is_radio_point)
					return
						($plugin_cookies_playback_udp->enabled == ControlSwitchDefs::switch_on)? UserInputHandlerRegistry::create_action($this->plugin->tv, 'launch_radio') : null;

				if (!is_null($this->plugin->tv->get_tv_playback_url($channel_id, 0, RET_LIVE_TEMPLATE_URL)))
				{
					$this->plugin->epg->tv_info_set_faulty(1);

					if ($this->plugin->tv->get_channel($channel_id)->is_adult())
						if (($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->tv->parental_passed)
							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));
				}

				return null;

			case GUI_EVENT_KEY_INFO:
				return
					$is_radio_point? null : $this->plugin->channels_editor->show_info($this);

			case 'show_channels_editor':
				return
					$is_radio_point? null : $this->plugin->channels_editor->show_editor($this);

			case GUI_EVENT_KEY_D_BLUE:
				if ($is_radio_point)
					return null;

				if (!$is_favorite)
					return $this->plugin->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_ADD, $channel_id, $plugin_cookies);

			case 'remove_favorite':
				if ($is_radio_point)
					return null;

				if ($is_favorite)
					return $this->plugin->tv->change_tv_favorites(PLUGIN_FAVORITES_OP_REMOVE, $channel_id, $plugin_cookies);

				break;

			case 'move_to_recycle_bin':
				if ($is_radio_point)
					return null;

				$exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();
				array_push($exclude_channel_ids, $channel_id);
				$this->plugin->tv->set_exclude_channel_ids($exclude_channel_ids);
				$sel_ndx = empty($sel_ndx)? 0 : $user_input->sel_ndx - 1;
				$range = $this->get_folder_range(MediaURL::decode($user_input->parent_media_url), 0, $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);

			case GUI_EVENT_KEY_B_GREEN:
				return
					$this->plugin->sorter->show($this, &$this->plugin->tv->channels);

			case 'multiple_edit_show':
				$add_params =
					array
					(
						'phase' => 0,
						'title_combo_id' => 'ignore',
						'icon_url_combo_id' => 'ignore',
						'subchannel_combo_id' => 'ignore',
						'epg_id_combo_id' => 'ignore',
						'live_url_combo_id' => 'ignore',
						'tv_archive_url_combo_id' => 'ignore',
						'epg_timeshift_combo_id' => 'ignore',
						'zoom_combo_id' => 'ignore',
						'deint_combo_id' => 'ignore',
					);

				return
					ActionFactorySafe::show_dialog(
						'Групповое редактирование',
						$this->get_multiple_edit_dialog_controls_defs($add_params),
						false,
						1300,
						array
						(
							ShowDialogActionData::actions =>
								array
								(
									GUI_EVENT_KEY_RETURN => ActionFactorySafe::close_dialog_and_run(UserInputHandlerRegistry::create_action($this, 'multiple_edit_close_dialog')),
								),
						)
					);

			case 'multiple_edit_continue':
				$add_params['phase'] = 2;

				foreach ($add_params as $param => $value)
				{
					if ($param == 'phase')
						continue;

					if ($value == 'ignore')
						unset($add_params[$param]);
					else
						$add_params['phase'] = 1;
				}

				$add_params['groups_combo_id'] = $selected_media_url->group_id;

				return
					ActionFactorySafe::reset_controls($this->get_multiple_edit_dialog_controls_defs($add_params), null, 0);

			case 'multiple_edit_apply':
				$group = ($add_params['groups_combo_id'] <> HomeTv::FAV_CHANNELS_GROUP_ID)? $this->plugin->tv->get_group($add_params['groups_combo_id']) : array('channels' => $this->plugin->tv->get_fav_channel_ids($plugin_cookies));
				$add_params['phase'] = 3;
				$add_params['ch_count'] = count($group['channels']);

				if (!empty($group['channels']))
				{
					foreach ($group['channels'] as $channel_id)
					{
						$this->plugin->user_data->select($channel_id);

						foreach ($add_params as $param => $value)
						{
							switch ($param)
							{
								case 'title_combo_id':
									$this->plugin->user_data->title = null;
									break;

								case 'icon_url_combo_id':
									$this->plugin->user_data->icon_url = null;
									break;

								case 'subchannel_combo_id':
									$this->plugin->user_data->subchannel_id = null;
									break;

								case 'epg_id_combo_id':
									$this->plugin->user_data->epg_id = empty($value)? null : $value;
									break;

								case 'live_url_combo_id':
									$this->plugin->user_data->live_streaming_url = null;
									break;

								case 'tv_archive_url_combo_id':
									$this->plugin->user_data->tv_archive_url = null;
									break;

								case 'epg_timeshift_combo_id':
									$this->plugin->user_data->epg_timeshift = empty($value)? null : $value;
									break;

								case 'zoom_combo_id':
									$this->plugin->user_data->zoom = ($value == 'default')? null : $value;
									break;

								case 'deint_combo_id':
									$this->plugin->user_data->deint = ($value == 'default')? null : $value;
									break;
							}
						}

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

						if ($channel->is_hd())
						{
							$channel->add_group(HomeTv::HDTV_CHANNELS_GROUP_ID);
							$this->plugin->tv->groups[HomeTv::HDTV_CHANNELS_GROUP_ID]['channels'][$channel_id] = $channel_id;
						}
						else
						{
							$channel->remove_group(HomeTv::HDTV_CHANNELS_GROUP_ID);
							unset($this->plugin->tv->groups[HomeTv::HDTV_CHANNELS_GROUP_ID]['channels'][$channel_id]);
						}

						$this->plugin->tv->channels->replace($channel);
					}

					$this->plugin->user_data->save();
				}

				return
					ActionFactorySafe::reset_controls($this->get_multiple_edit_dialog_controls_defs($add_params), null, 0);

			case 'multiple_edit_close_dialog':
				$changed_successfully = ($add_params['phase'] == 3) && !empty($add_params['ch_count']);

				if (!$changed_successfully)
					return null;

			case 'update_parent_folders':
				$this->plugin->sorter->sort_channels($plugin_cookies, &$this->plugin->tv->channels);
				$range = $this->get_folder_range(MediaURL::decode($user_input->parent_media_url), 0, $plugin_cookies);
				$post_action = ActionFactorySafe::update_regular_folder($range, true, -1);

				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);

			case GUI_EVENT_KEY_POPUP_MENU:
				if (!$is_radio_point && $this->plugin->tv->favorites_enabled)
				{
					if (!$is_favorite)
						$popup_menu_items[] =
							array
							(
								GuiMenuItemDef::caption => 'Добавить в Избранное',
								GuiMenuItemDef::icon_url => 'plugin_file://img/star_add.png',
								GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_D_BLUE),
							);
					else
						$popup_menu_items[] =
							array
							(
								GuiMenuItemDef::caption => 'Удалить из Избранного',
								GuiMenuItemDef::icon_url => 'plugin_file://img/star_rem.png',
								GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'remove_favorite'),
							);
				}

				if (!$is_radio_point)
				{
					$popup_menu_items[] =
						array
						(
							GuiMenuItemDef::caption => 'Удалить в корзину',
							GuiMenuItemDef::icon_url => 'plugin_file://img/bin.png',
							GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'move_to_recycle_bin'),
						);
					$popup_menu_items[] = array(GuiMenuItemDef::is_separator => true);
				}

				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Сортировка каналов',
						GuiMenuItemDef::icon_url => 'plugin_file://img/sort.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_B_GREEN),
					);
				$popup_menu_items[] = array(GuiMenuItemDef::is_separator => true);

				if (!$is_radio_point)
				{
					$popup_menu_items[] =
						array
						(
							GuiMenuItemDef::caption => 'Редактировать канал',
							GuiMenuItemDef::icon_url => 'plugin_file://img/channels_editor.png',
							GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'show_channels_editor'),
						);
					$popup_menu_items[] = array(GuiMenuItemDef::is_separator => true);
				}
				$popup_menu_items[] =
					array
					(
						GuiMenuItemDef::caption => 'Групповое редактирование',
						GuiMenuItemDef::icon_url => 'plugin_file://img/multiple_edit.png',
						GuiMenuItemDef::action => UserInputHandlerRegistry::create_action($this, 'multiple_edit_show'),
					);

				return
					ActionFactorySafe::show_popup_menu($popup_menu_items);

			default:
				if (isset($user_input->control_id))
				{
					$control_id = $user_input->control_id . '_id';
					$add_params[$control_id] = $user_input->{$user_input->control_id};

					return
						ActionFactorySafe::reset_controls($this->get_multiple_edit_dialog_controls_defs($add_params));
				}
		}

		return null;
	}

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

	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
		$this->plugin->tv->folder_entered($media_url, $plugin_cookies);
		$this->plugin->tv->ensure_channels_loaded($plugin_cookies);

		try
		{
			$group = $this->plugin->tv->get_group($media_url->group_id);
		}
		catch (Exception $e)
		{
			throw new Exception(get_class($this)." ({$this->get_handler_id()}): Group {$media_url->group_id} not found.");
			return null;
		}

		$items = array();
		$favorites_enable = ($plugin_cookies->favorites_enable == ControlSwitchDefs::switch_on);
		$tv_fav_channel_ids = $this->plugin->tv->get_fav_channel_ids($plugin_cookies);
		$tv_exclude_channel_ids = $this->plugin->tv->get_exclude_channel_ids();
		$left_margin = ControlFactoryExt::get_left_margin_str(12);

		foreach ($this->plugin->tv->get_channels() as $channel_id => $channel)
		{
			if (!in_array($channel_id, $group['channels']) || in_array($channel_id, $tv_exclude_channel_ids))
				continue;

			$is_corrupted = 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));

			if ((self::$browse_mode == TvBrowseModeDefs::normal) && $is_corrupted)
				continue;

			$item_idx = count($items);
			$title = $channel->get_title();
			$icon_url = $channel->get_icon_url();
			$num_length = strlen($channel->get_number());

			$items[] =
				array
				(
					PluginRegularFolderItem::media_url =>
						MediaURL::encode(
							array
							(
								'group_id' => $media_url->group_id,
								'channel_id' => $channel_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)),
							FolderViewItemParams::icon_path => $icon_url,
							FolderViewItemParams::item_detailed_icon_path => $icon_url,
							FolderViewItemParams::item_detailed_info => "|| ||{$title}| ||{$channel->get_desc()}",
							FolderViewItemParams::item_detailed_icon_width => 460,
							FolderViewItemParams::item_detailed_icon_height => 260,
							FolderViewItemParams::item_badge_icon_path => ($favorites_enable && in_array($channel_id, $tv_fav_channel_ids))? 'plugin_file://img/channel_fav_badge.png' : 'plugin_file://img/channel_badge.png',
						),
				);

			if ($is_corrupted)
				$items[$item_idx][PluginRegularFolderItem::view_item_params][FolderViewItemParams::item_caption_color] = DEF_LABEL_TEXT_COLOR_DIMGRAY;
		}

		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);

		if ($media_url->group_id == HomeTv::RADIO_POINTS_GROUP_ID)
		{
			$folder_view[PluginFolderView::data][PluginRegularFolderView::view_params][FolderViewParams::background_path] = 'plugin_file://img/bg/main_screen_radio_points_list.png';
			$folder_view[PluginFolderView::data][PluginRegularFolderView::view_params][FolderViewParams::item_detailed_info_rel_y] = parent::get_folder_view_index($plugin_cookies)? 392 : 280;
		}

		if (self::$browse_mode == TvBrowseModeDefs::full)
			$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;
	}
}

?>
