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

require_once 'lib/abstract_controls_screen.php';

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

class MyPlugIN_SetupScreen extends AbstractControlsScreen
{
    const ID = 'setup';
    private $session;
    ///////////////////////////////////////////////////////////////////////
   public static function get_media_url_str()
    {
        return MediaURL::encode(
            array
            (
                'screen_id' => self::ID,
            ));
    }
    public function __construct($session,$tv)
    {
        parent::__construct(self::ID);

        $this->session = $session;
        $this->tv = $tv;
    }

    public function do_get_control_defs(&$plugin_cookies)
    {
       $defs = array();
       $show_tv = isset($plugin_cookies->show_tv) ?
            $plugin_cookies->show_tv : 'yes';
        $show_vod = isset($plugin_cookies->show_vod) ?
            $plugin_cookies->show_vod : 'yes';
	$islogged = $this->session->is_logged_in();
	hd_print("is_logged->>>>: $islogged");
	$is_login_correct = isset($plugin_cookies->is_login_correct) ? $plugin_cookies->is_login_correct : false;
	hd_print("is_login_correct:$is_login_correct");
	if ($is_login_correct == 1 && $islogged == 0)
	{
		hd_print("попытка авторизации");
		$this->session->login_mylogin ($plugin_cookies);
	}

			#$this->session->get_acc_settings($plugin_cookies);
			#$acc_info = $this->session->get_account();
			#$acc_title = isset($acc_info->login) ? strval($acc_info->login) : 'Недоступно';
			#hd_print("acc_title: $acc_title");
			#$acc_packet_name = isset($acc_info->packet_name) ? strval($acc_info->packet_name) : 'Недоступно';
			#hd_print("acc_packet_name:$acc_packet_name");
			#$acc_tmp = isset($acc_info->packet_expire) ? intval($acc_info->packet_expire) : 0;
			#hd_print("time:$acc_tmp");
			#$acc_subscr_end = date("d.m.y",$acc_tmp) . " " . date("H:i",$acc_tmp);
			#$acc_settings = $this->session->get_settings();
			#$acc_time_shift = isset($acc_settings->timeshift->value) ? strval($acc_settings->timeshift->value) : "недоступно";
			$acc_settings = $this->session->get_sett();
			$acc_time_shift = isset($plugin_cookies->time_shift) ? strval($acc_settings->time_shift) : 0;
			
			
			
			hd_print("timeshift:$acc_time_shift");
			$time_shift_ops = array();
			for ($i=0; $i<=24; $i++) {
			$time_shift_ops[$i] = $i;
			}
			$stream_server = isset($plugin_cookies->stream_server) ? strval($acc_settings->media_server_id) : 0;
			
			hd_print("stream_server:$stream_server");
			$stream_server_ops = Array();
			foreach ($acc_settings->media_servers->item as $server) {
			$stream_server_ops[strval($server->id)] = strval($server->title);
			}
			$epg_shift = isset($plugin_cookies->epg_shift) ? strval($acc_settings->time_zone) : '0';
			for ($i = -12; $i<13; $i++)
			$shift_ops[$i*60] = $i;
			
			$buf_time = isset($plugin_cookies->buf_time) ? $plugin_cookies->buf_time : 1000;
			hd_print("buff:$buf_time");
			$show_buf_time_ops = array();
			$show_buf_time_ops['500'] = '500';
			$show_buf_time_ops['1000'] = '1000 (по умолчанию)';
			$show_buf_time_ops['1500'] = '1500';
			$show_buf_time_ops['2000'] = '2000';
			$show_buf_time_ops['2500'] = '2500';
			$show_buf_time_ops['3000'] = '3000';
			$show_buf_time_ops['5000'] = '5000';
			$show_buf_time_ops['10000']	= '10000';
		
        $this->add_button($defs, 'edit_subscription', null,
            'Изменить пользователя', 0);

			$this->add_button($defs, 'edit_pcode','Код закрытх каналов:',
                'Сменить...', 0);
        		$this->add_combobox
        		(
            			$defs,
            			'http_caching',
            			'Время буферизации:',
            			$buf_time, $show_buf_time_ops, 0, true
        		);

			       			$this->add_combobox
        			(
            				$defs,
            				'timeshift',
            				'Таймшифт:',
            				$acc_time_shift,$time_shift_ops, 0, true
        			);
			$this->add_combobox($defs,
            'epg_shift', 'Коррекция программы (час):',
            $epg_shift, $shift_ops, 0, true);
			/*$this->add_combobox
        		(
            			$defs,
            			'bitrate',
            			'Битрейт:',
            			$acc_bitrate, $show_bitrate_ops, 0, true
        		);*/
		    $this->add_combobox
			    ($defs,
			     'stream_server',
			    'Сервер:',
			    $stream_server, 
			    $stream_server_ops,
			    0,
			    true);

			#$this->add_label($defs,'Код закрытх каналов:', 'не доступно');
			#$this->add_label($defs,'Время буферизации:', 'не доступно');
			#$this->add_label($defs,'Таймшифт:', 'не доступно');
			#$this->add_label($defs,'Битрейт:', 'не доступно');
			#$this->add_label($defs,'Сервер:', 'не доступно');
			
 	$this->add_label($defs,'OZO.tv Plugin ', 'Версия:1.1');
        return $defs;
    }
            

    public function get_control_defs(MediaURL $media_url, &$plugin_cookies)
    {
        $this->tv->unload_channels();
        return $this->do_get_control_defs($plugin_cookies);
    }

    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");
	$need_close_dialog = false;
	$need_reset_controls = false;
	$post_action = null;
        #hd_print("Setup: changing $control_id value to $new_value");

        if ($user_input->action_type === 'confirm')
        {

        	$control_id = $user_input->control_id;
        	$new_value = $user_input->{$control_id};	    
            if ($control_id === 'show_tv')
                $plugin_cookies->show_tv = $new_value;
            else if ($control_id === 'show_vod')
                $plugin_cookies->show_vod = $new_value;


				else if($control_id === 'http_caching')
				{
					$buf_time = intval($new_value);
					$plugin_cookies->buf_time = $buf_time;
				}
		else if ($control_id === 'timeshift')
		{
		$p_var = $new_value;
		$plugin_cookies->time_shift = $new_value;
		$this->session->set_set_pro($control_id, $p_var);
		}
		else if ($control_id === 'epg_shift')
		{
        $plugin_cookies->epg_shift = $new_value;
		$this->session->set_set_pro($control_id, $new_value);
		}
		else if ($control_id === 'stream_server')
		{
		$p_var = $new_value;
		$plugin_cookies->stream_server = $new_value;
		$this->session->set_set_pro($control_id, $p_var);
		}
            $need_reset_controls = true;
        }
        else if ($user_input->action_type === 'apply')
        {
	    $control_id = $user_input->control_id;
	    hd_print("idcon:$control_id");
	    if ($control_id === 'edit_subscription')
		{
			return $this->do_get_edit_subscription_action($plugin_cookies, $this);
		}
            else if ($control_id === 'edit_pcode')
		{
			hd_print("pcod");
			return $this->do_get_edit_pcode_action();
		}
	    elseif ($control_id === 'apply_sub')
		{
			if ($user_input->login === '' || $user_input->pass === '')
				{
					return ActionFactory::show_error(false,'Error',array('Поле Логин или Пароль не может быть пустым.'));
				}
				

			$islogged = $this->session->is_logged_in();
			if ($islogged == true)
				{
					$this->session->unset_login();
				}
			try
				{
					$this->session->login_mylogin2($user_input->login, $user_input->pass, &$plugin_cookies);
				}
			catch (DuneException $e)
				{
					return $this->session->api_exception($e,'login failed.', false);
					#$post_action = $e->get_error_action();
				}
			#$plugin_cookies->is_login_correct = $this->session->is_logged_in();
				hd_print("---------------------------------");
			if ($plugin_cookies->is_login_correct == true)
								{$plugin_cookies->login = $user_input->login;
								$plugin_cookies->pass = $user_input->pass;}
			/*if ($plugin_cookies->is_login_correct == false)
				{
					return ActionFactory::show_error(false,'Error',array('Неправильный логин или пароль'));
				}*/
			$need_close_dialog = true;
                	$need_reset_controls = true;
                	#$plugin_cookies->logiin = true;
			hd_print("gfhdhfh");
		}
	    elseif ($control_id === 'pcode')
	    {
		$p_var = '&var=parental_pass&val='.$user_input->new_pcode.'&protect_code='.$user_input->current_pcode;//'&old_code='.$user_input->current_pcode.'&new_code='.$user_input->new_pcode.'&confirm_code='.$user_input->new_pcode_copy;
		
		$this->session->set_settings($control_id, $p_var);
  		$need_reset_controls = true;
  		$need_close_dialog = true;
  	    }
	    elseif ($control_id === 'close')
	    {
	     //return null;
  		$need_reset_controls = true;
  		$need_close_dialog = true;
  	    }
	    else
	    {
	     //return null;
  		$need_reset_controls = true;
  		$need_close_dialog = true;
  	    }
        }
	if ($need_reset_controls)
        {
            $defs = $this->do_get_control_defs($plugin_cookies);
	    hd_print("uuuuuuuuuuuuu");
            $reset_controls_action = ActionFactory::reset_controls(
                $defs, $post_action);

            if ($need_close_dialog)
            {
                return ActionFactory::close_dialog_and_run(
                    $reset_controls_action);
            }

            return $reset_controls_action;
         }
        #return ActionFactory::reset_controls(
        #    $this->do_get_control_defs($plugin_cookies));
    }

    public function do_get_edit_subscription_defs(&$plugin_cookies, $handler, $add_params)
	{
		$defs = array();
		
		$login = isset($plugin_cookies->login) ? $plugin_cookies->login : '';
        	$pass = isset($plugin_cookies->pass) ? $plugin_cookies->pass : '';
		ControlFactory::add_text_field($defs,
            		$handler, $add_params,
            			'login', 'Логин:',
            			$login, 0, 0, 0, 1, 400, 0, true);
        	ControlFactory::add_text_field($defs,
            		$handler, $add_params,
            		'pass', 'Пароль:',
            		$pass, 0, 1, 0, 1, 400, 0, true);

        	ControlFactory::add_vgap($defs, 50);

        	ControlFactory::add_button($defs,
            		$handler, $add_params,
            		'apply_sub', null, 'Сохранить', 300);

        	ControlFactory::add_vgap($defs, -3);
        	ControlFactory::add_button($defs,$handler,$add_params,
            					'close',null,'Отменить', 300);

        	#ControlFactory::add_close_dialog_button($defs,
            	#					'Отменить', 300);

        	return $defs;
	}  
   public function do_get_edit_subscription_action(&$plugin_cookies, $handler, $add_params = null) 
	{
		$message = 'Введите данные логин и пароль';
        	return ActionFactory::show_dialog(
            		$message,
            		$this->do_get_edit_subscription_defs(
                	$plugin_cookies, $handler, $add_params),
            		true);

	}

    private function do_get_edit_pcode_defs()
    {
        $defs = array();

        $this->add_text_field($defs,
            'current_pcode', 'Текущий код:',
            '', true, true, false,false,500);

        $this->add_text_field($defs,
            'new_pcode', 'Новый код:',
            '', true, true, false,false,500);

        $this->add_text_field($defs,
            'new_pcode_copy', 'Код потверждения',
            '', true, true, false,false,500);

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

        $this->add_button($defs,
            'pcode', null, 'Добавить', 300);

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

        $this->add_close_dialog_button($defs,
            'Отменить', 300);

        return $defs;
    }

    private function do_get_edit_pcode_action()
    {
        return ActionFactory::show_dialog(
            'Смена кода для закрытых каналов',
            $this->do_get_edit_pcode_defs(),
            true);
    }


}

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