<?php
///////////////////////////////////////////////////////////////////////////
require_once 'lib/abstract_preloaded_regular_screen.php';
require_once 'lib/abstract_controls_screen.php';
require_once 'flussonic_m3u_tv.php';
//require_once 'flussonic_main_screen.php';
///////////////////////////////////////////////////////////////////////////

class FlussonicSetupScreen extends AbstractControlsScreen
{
    const ID = 'setup';
    ///////////////////////////////////////////////////////////////////////
	public static function get_media_url_str()
    {
        return MediaURL::encode(
            array
            (
                'screen_id' => self::ID,
            ));
    }
	protected $tv;
    public function __construct(Tv $tv)
    {
        parent::__construct(self::ID);
      $this->tv = $tv;
    }
	
    public function do_get_control_defs(&$plugin_cookies)
    {
        $defs = array();
		
		$pass_sex = isset($plugin_cookies->pass_sex) ?  $plugin_cookies->pass_sex : '1234';

        $show_tv = isset($plugin_cookies->show_tv) ? $plugin_cookies->show_tv : 'yes';

        $format = isset($plugin_cookies->format) ? $plugin_cookies->format : 'hls+UTC-Archivetime';

		$show_icons = isset($plugin_cookies->show_icons) ? $plugin_cookies->show_icons : '/D/';
		
		//$epg_shift = isset($plugin_cookies->epg_shift) ? 
		//	$plugin_cookies->epg_shift : '0';
		
		$epg_font_size = isset($plugin_cookies->epg_font_size) ? $plugin_cookies->epg_font_size : 'NORMAL';
		
		$token = isset($plugin_cookies->token) ? $plugin_cookies->token : '0';

		if(isset($plugin_cookies->billing_id)){
			$billing_id = $plugin_cookies->billing_id;
		} else {
			$billing_id = 1;
			$plugin_cookies->billing_id = $billing_id;
		}
		
		$buffering_time = isset($plugin_cookies->buffering_time) ? $plugin_cookies->buffering_time : '1000';
		/////////////////////////////////////////////////////////////////////////
		for ($i = -12; $i<13; $i++)
		$shift_ops[$i*3600] = $i;
	
        $show_ops = array();
        $show_ops['yes'] = '%tr%t9'; //Да
        $show_ops['no'] = '%tr%t10'; //Нет

		$show_my = isset($plugin_cookies->show_my) ? $plugin_cookies->show_my : dirname(__FILE__) . '/playlist.m3u';
			
		ControlFactory::add_vgap($defs, -10);
		$this->add_label($defs, '%tr%t3', 'Ver.  ' .FlussonicConfig::PluginVersion.' ['.FlussonicConfig::PluginDate.']'); //Приложение SCHURIK TV
	

		// package info region
		if(!isset($token) || trim($token) == "0"){
			$packet_info = array();
		} else {
			$packet_info = FlussonicConfig::get_packet_info(sprintf(FlussonicConfig::USER_INFO, $token), $billing_id);
		}

		if (count($packet_info) === 0){
			$this->add_label($defs, '%tr%t40', "%tr%t50"); // Пакет , "Не веден ключ"
			$this->add_label($defs, '%tr%t41', "-"); // Действителен до , -
		} else {
			$this->add_label($defs, '%tr%t40', $packet_info[0]['packet']); // Пакет
			if ($packet_info[0]['exp'] == '404' || $packet_info[0]['exp'] == '401' || $packet_info[0]['exp'] == '0'){
				$this->add_label($defs, '%tr%t41', '-'); // Действителен до, -
			} else {
				$this->add_label($defs, '%tr%t41', $packet_info[0]['exp']); // Действителен до
			}
		}
		//endregion

		//$this->add_label($defs, '-----------------------------------------', '-----------------------------'); // Настройки
		
		$this->add_button($defs, 'edit_token','%tr%t6', //Активировать просмотр:
			'%tr%t7', 0); //Введите ключ

		$this->add_combobox($defs, 'show_tv', '%tr%t8', //Отображать в ТВ:
            $show_tv, $show_ops, 0, true);

       	//$this->add_combobox($defs,
        //    'epg_shift', 'Коррекция программы (час):',
        //    $epg_shift, $shift_ops, 0, true);
		
		$buffering_ops = array();
			$buffering_ops['500'] = '500';
			$buffering_ops['1000'] = '%tr%t11'; //1000 (по умолчанию)
			$buffering_ops['1500'] = '1500';
			$buffering_ops['2000'] = '2000';
			$buffering_ops['2500'] = '2500';
			$buffering_ops['3000'] = '3000';
			$buffering_ops['4000'] = '4000';
			$buffering_ops['5000'] = '5000';
			$buffering_ops['6000'] = '6000';
			$buffering_ops['8000'] = '8000';
			$buffering_ops['10000']	= '10000';
			$buffering_ops['15000']	= '15000';
			$buffering_ops['20000']	= '20000';
			$buffering_ops['25000']	= '25000';
			$buffering_ops['30000']	= '30000';
			$buffering_ops['35000']	= '35000';
			$buffering_ops['45000']	= '45000';
			$buffering_ops['50000']	= '50000';
			
		$this->add_combobox($defs,
            'buffering_time', '%tr%t12',
            $buffering_time, $buffering_ops, 0, true);
			
		$epg_font_size_ops = array();
			$epg_font_size_ops['NORMAL'] = '%tr%t14';
			$epg_font_size_ops['SMALL']  = '%tr%t15';
		
		$this->add_combobox($defs,
            'epg_font_size', '%tr%t13', //Размер шрифта EPG:
            $epg_font_size, $epg_font_size_ops, 0, true);

    $format_ops = array();
			$format_ops['hls'] = 'hls';
			$format_ops['hls+video.m3u8'] = 'hls+video.m3u8';
			$format_ops['hls+UTC-Archivetime'] = 'hls+UTC-Archivetime';
            //$format_ops['hlsffmpeg'] = 'hls+ffmpeg';
			$format_ops['mpeg'] = 'mpeg';
			//$format_ops['mpd'] = 'DASH';

        $this->add_combobox($defs,
            'format', '%tr%t16', //Тип потоков:
			$format, $format_ops, 0, true);
			
		$this->add_button($defs, 'pass_dialog', '%tr%t17', '%tr%t18', 0);	//Пароль для взрослых каналов:, Изменить пароль
		$this->add_button($defs, 'restart', '%tr%t29','%tr%t51', 0 ); 
			
		//////////////////////////////////////////////////////////////////////////
			$my_dir_ops = array();
			
				$my_dir_ops[dirname(__FILE__) . '/playlist.m3u'] = dirname(__FILE__) . '/playlist.m3u';

					foreach (glob('/D/*.m3u') as $file) {
					//hd_print("-------$file");
					if(strlen($file) > 36)
					$ur = substr($file, -30);
					else
						$ur = $file;
					$my_dir_ops[$file] = $ur;
					//hd_print("-------$file");
					}
			//}
			
			 /*$this->add_combobox($defs,
            	'show_my', 'Каталог c листом:',
            	$show_my, $my_dir_ops, 0, true);
				*/
				$my_dir_icons = array();
			

					foreach (glob('/D/*') as $file) {
					$my_dir_icons[$file] = $file;
					//hd_print("-------$file");
					}
				/*$this->add_combobox($defs,
            	'show_icons', 'Каталог c картин...:',
            	$show_icons, $my_dir_icons, 0, true);*/	
        return $defs;
    }

    public function get_control_defs(MediaURL $media_url, &$plugin_cookies)
    {
        return $this->do_get_control_defs($plugin_cookies);
	}
	
	public function do_get_pass_control_defs(&$plugin_cookies)
    {
        $defs = array();

        $pass1 = '';
        $pass2 = '';

        $this->add_text_field($defs, 'pass1', '%tr%t19', $pass1, 1, 1, 0, 1, 500, 0, false); //Старый пароль:
        $this->add_text_field($defs, 'pass2', '%tr%t20', $pass2, 1, 1, 0, 1, 500, 0, false); //Новый пароль:

        $this->add_label($defs, '', '');

        $this->add_close_dialog_and_apply_button($defs, 'pass_apply', 'ОК', 250);
        $this->add_close_dialog_button($defs, '%tr%t21', 250); //Отмена

        return $defs;
    }

    public function handle_user_input(&$user_input, &$plugin_cookies)
    {
        hd_print('Setup: handle_user_input:');
        foreach ($user_input as $key => $value)
            hd_print("  $key => $value");

        if ($user_input->control_id === 'edit_token')
			return $this->do_get_edit_pcode_action(&$plugin_cookies);
		        
		else if ($user_input->control_id === 'pcode'){
			
			$plugin_cookies->token = $user_input->current_pcode;
			////////////////////////////////CHECK FOR ABO
			$source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST."/ott/m3u8-dune/".$user_input->current_pcode."/playlist.m3u8"));
			//hd_print("-".$source."-");

			$this->tv->unload_channels();
			$this->tv->load_channels(&$plugin_cookies);	
			
			if ($source === "nottoken" || $source == "Token not found"){
				hd_print("trying other plylist");
				$source = HD::check_token(trim(FlussonicConfig::CHANNEL_LIST_HOST2."/pl/m3u8-dune/".$plugin_cookies->token."/pl.m3u8")); //если первый не идёт, скачать этот
				$plugin_cookies->billing_id = 2;
			} else {
				$plugin_cookies->billing_id = 1;
			}

			if ($source === "nottoken" || $source == ""){
				hd_print("none of the playlists works");
				// return ActionFactory::show_title_dialog("%tr%t22"); //К сожалению, ключ не активирован или введён с ошибкой!
			}

			$perform_new_action = UserInputHandlerRegistry::create_action($this, 'reset_controls');
			
			return ActionFactory::close_dialog_and_run(ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action));
		}		
		
		else if ($user_input->action_type === 'confirm' || $user_input->action_type === 'apply')
        {
            $control_id = $user_input->control_id;
            $new_value = $user_input->{$control_id};
            hd_print("Setup: changing $control_id value to $new_value");

			if ($control_id === 'restart'){
                //shell_exec('killall shell'); 
                shell_exec('killall com.dunehd.shell');
			}
            if ($control_id === 'show_tv')
                $plugin_cookies->show_tv = $new_value;
            //else if ($control_id === 'epg_shift')
			//	$plugin_cookies->epg_shift = $new_value;
			else if ($control_id === 'format'){
				if($new_value === 'hlsffmpeg'){
					$test = file_get_contents("http://127.0.0.1:81/cgi-bin/hls.sh");
						if(!$test)
							return ActionFactory::show_title_dialog("Кодеки не найдены");
						else
							$plugin_cookies->format = $new_value;
				}
				else
				$plugin_cookies->format = $new_value;
			}
			else if ($control_id === 'epg_font_size')
                $plugin_cookies->epg_font_size = $new_value;
			else if ($control_id == 'buffering_time')
				$plugin_cookies->buffering_time = $new_value;
			else if ($control_id === 'show_icons') 
                $plugin_cookies->show_icons = $new_value;
			else if ($control_id === 'show_my'){
			
                $plugin_cookies->show_my = $new_value;
			$this->tv->unload_channels();
			$this->tv->load_channels(&$plugin_cookies);
			$perform_new_action = UserInputHandlerRegistry::create_action(
                    $this, 'reset_controls');
				return ActionFactory::invalidate_folders(array('tv_group_list'), $perform_new_action);	
			}

			else if ($control_id === 'pass_dialog') {
                $defs = $this->do_get_pass_control_defs($plugin_cookies);

                return ActionFactory::show_dialog("%tr%t23", $defs, true); //Родительский контроль
            } else if ($control_id === 'pass_apply') {
                if ($user_input->pass1 == '' || $user_input->pass2 == '')
                    return null;
                $msg      = '';
                $action   = null;
                $pass_sex = isset($plugin_cookies->pass_sex) ? $plugin_cookies->pass_sex : '1234';
                if ($user_input->pass1 == $pass_sex) {
                    $plugin_cookies->pass_sex = $user_input->{'pass2'};
                    $msg = '%tr%t24'; //Пароль изменен!
                } else {
                    $msg = '%tr%t25'; //Пароль не изменен!
                }

                return ActionFactory::show_title_dialog($msg, $action);
            }
        }

        return ActionFactory::reset_controls(
            $this->do_get_control_defs($plugin_cookies));
    }
	private function do_get_edit_pcode_defs(&$plugin_cookies)
    {
        $defs = array();

        $this->add_text_field($defs,
            'current_pcode', '%tr%t26', //Ключ
            $plugin_cookies->token,  false, false, false, true, 500);

        $this->add_vgap($defs, 50);

        $this->add_button($defs,'pcode', null, '%tr%t27', 300); //Применить
			
		$this->add_close_dialog_button($defs,'%tr%t28', 300); //Закрыть

        

        return $defs;
    }

    private function do_get_edit_pcode_action(&$plugin_cookies)
    {
        return ActionFactory::show_dialog(
            '%tr%t7', //Введите ключ
            $this->do_get_edit_pcode_defs(&$plugin_cookies),
            true);
    }
}

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