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

class MyPlugIN_Api
{ 
	const API_URL = 'http://core.ozo.tv/iptv/api/v1/xml/';
	#const API_URL = '';
	private $cookie = null;
	public $settings = null;
	public $account = null;
	private $is_logged = null;
	private $disk_space = 0;


	public function is_logged_in()
	{ return $this->is_logged; }

	public function get_account()
	{ return $this->account; }

	public function get_settings()
	{ return $this->settings; }

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

    	public function api_exception($e, $def_caption, $is_playback)
	{
		$is_mylogin_error = ($e instanceof MyPlugIN_Exception);
        	if (!$is_mylogin_error)
        	{
            		hd_print('General exception: ' . $e->getMessage());
            		$title = !$is_playback ? 'Оповещение' :
                	'Не удалось подключиться к Интернету.';
            		$text_lines = $is_playback ? array() :
                	array(
                 		//'Не удалось подключиться к Интернету.',
                 		$e->getMessage()
                		);
            		return new DuneException(
                	$def_caption, -1,
                		ActionFactory::show_error(false, $title, $text_lines));
						
        	}
        	hd_print('MyPlugIN API exception: ' .
            		'code=' . $e->getCode() . ', message=' . $e->getMessage());

        	$ecode = $e->getCode();
		$emessage = $e->getMessage();
        	#$fatal = $ecode == 5 || $ecode == 6 ||
            		#$ecode == 11 || $ecode == 12 || $ecode == 13;

		$fatal = $ecode == 12 && $emessage == 'Authentification error' || $ecode == 17 || $ecode == 5;
        	if ($fatal)
            		$this->unset_login();

		#if ($ecode == 2 || $ecode == 4)
		#	{
		#		$this->is_logged = false;
		#	}
        	$title = !$is_playback ? 'Error' : $emessage;
        	$text_lines = $is_playback ? array() :
            	array('Описание: ' . $emessage,
                	'Код ошибки: ' . $ecode);
        	return new DuneException(
            		$def_caption, $ecode,
            		ActionFactory::show_error($fatal, $title, $text_lines));
		
	}
///////////////////////////////////////////////////////////////////////////
	public function unset_login()
	{
		hd_print("unset_login");
		$this->cookie = null;
		$this->is_logged = false;
		$this->account = null;
		$this->settings = null;
		
	}
///////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////
	public function check_login($plugin_cookies)
	{
		hd_print("check_login");
		hd_print("cookie:$this->cookie");
		$is_login_correct = isset($plugin_cookies->is_login_correct) ? $plugin_cookies->is_login_correct : false;
		hd_print("is_login_corect:$is_login_correct");
		$is_logged = $this->is_logged_in();
		hd_print("is_logged:$is_logged");
		$is_log = isset($is_logged) ? $is_logged : false;
		if ($is_login_correct == 1 && $is_logged != 1)
		{
			hd_print("Авторизация>");
			$this->login_mylogin($plugin_cookies);
			hd_print("cookie1:$this->cookie");
		}	
	}

///////////////////////////////////////////////////////////////////////////
	public function logout()
	{
		$this->unset_login();
	}
///////////////////////////////////////////////////////////////////////////
	public function get_sett()
	{

			$set = HD::http_get_document(self::API_URL . 'get_settings?sid='.$this->cookie);
			$set = simplexml_load_string($set);

		return $set;
	}
	public function login_mylogin($plugin_cookies)
	{
		if (!isset($plugin_cookies->login))
            		throw new Exception('Логин не введен');
		if (!isset($plugin_cookies->pass))
            		throw new Exception('Пароль не введен');
		$doc = self::API_URL . 'login?login='. $plugin_cookies->login.'&pass='.md5(md5($plugin_cookies->login).md5($plugin_cookies->pass)).'&user_agent=dune_hd';
		//hd_print("--->>> get_login: $doc");
		/////////////////////////////////////////////////////
					
		try
		{
			$this->is_logged = true;
			$plugin_cookies->is_login_correct = true;
			$data = $this->json_fetch($doc,1);
		}
		catch (Exception $e)
		{
			$this->is_logged = false;
			hd_print("loged falled");
			$plugin_cookies->is_login_correct = false;
			throw $this->api_exception($e,'Ошибка авторизации', false);
		}
		if(isset($data->sid))
		{
			$this->cookie = strval($data->sid);
			$this->settings = $data->settings;
			$this->account = $data->account;
			$doc1 = HD::http_get_document(self::API_URL . '/get_account_info?sid='.$this->cookie);
			hd_print("---------$doc1");
			$doc1 = simplexml_load_string($doc1);
			$result = strval($doc1->subscriptions->item->rest_of_days);
			if ($result == '1')
			$day = 'день';
			else
			$day = 'дней';
			$title = 'Внимание! Ваша подписка заканчивается. Осталось: ';
			#$this->test_free_space();
			#try
			#{
			#	hd_print("bitrate");
			#	$this->set_settings('bitrate',4000);
			#}
			#catch (Exception $e)
			#{
			#	throw $this->api_exception($e,'Ошибка смены битрейта', false);
			#}
			

		}
		if ($result < '3') {
		try {
			$error = $title.$result. ' ' .$day;
			
			throw new Exception($error);

		// Code following an exception is not executed.
			//echo 'Never executed';

			} catch (Exception $e) {
			throw $this->api_exception($e,'General', false);
			}
		}
	}
	public function login_mylogin2($login, $pass, &$plugin_cookies)
	{
		$doc = self::API_URL . 'login?login='. $login.'&pass='.md5(md5($login).md5($pass)).'&user_agent=dune_hd';
		hd_print("--->>> get_login: $doc");
		/////////////////////////////////////////////////////
					
		try
		{
			$plugin_cookies->login = $login;
			$plugin_cookies->pass = $pass;
			$this->is_logged = true;
			$plugin_cookies->is_login_correct = true;
			$data = $this->json_fetch($doc,1);
		}
		catch (Exception $e)
		{
			$this->is_logged = false;
			hd_print("loged falled");
			$plugin_cookies->is_login_correct = false;
			throw $this->api_exception($e,'Ошибка авторизации', false);
		}
		if(isset($data->sid))
		{
			$this->cookie = strval($data->sid);
			$this->settings = $data->settings;
			$this->account = $data->account;
		}
	}
///////////////////////////////////////////////////////////////////////////
	public function login_mylogin1($plugin_cookies)
	{
		if (!isset($plugin_cookies->login))
            		throw new Exception('Логин не введен');
		if (!isset($plugin_cookies->pass))
            		throw new Exception('Пароль не введен');
		$doc = HD::http_get_document(self::API_URL . 'login?login='. $plugin_cookies->login.'&pass='.md5(md5($plugin_cookies->login).md5($plugin_cookies->pass)).'&user_agent=dune_hd');
		hd_print("--------$doc");
		$doc = simplexml_load_string($doc);
				if (isset($doc->error)) {
			$this->is_logged = FALSE;
			$plugin_cookies->is_login_correct = FALSE;
			}
		if(isset($doc->sid))
		{
			hd_print("okkkkkkkkkkkkkkkk");
			$this->is_logged = true;
			$plugin_cookies->is_login_correct = true;
			$data = $doc;
			$this->cookie = strval($data->sid);
			$set = HD::http_get_document(self::API_URL . 'get_settings?sid='.$this->cookie);
			hd_print("set--->$set");
			$set = simplexml_load_string($set);
			$this->settings = $set;
			$this->account = $data->account;
			$this->test_free_space();
			#try
			#{
			#	hd_print("bitrate");
			#	$this->set_settings('bitrate',4000);
			#}
			#catch (Exception $e)
			#{
			#	throw $this->api_exception($e,'Ошибка смены битрейта', false);
			#}
			

		}
		
	}
///////////////////////////////////////////////////////////////////////////
	public function test_free_space()
	{
		/*$plugin_dir = DuneSystem::$properties['install_dir_path'];
		$free_space = disk_free_space("$plugin_dir");
		$url_prefix = MyPlugIN_Config::ARCHIVE_URL;
		$size_url = $url_prefix . '/size.txt';
		$doc_ = HD::http_get_document($size_url);
		if (is_null($doc_))
            	{
                	hd_print("Failed to fetch archive size.txt from $size_url.");
			$this->disk_space = 0;
            	}
            	else
            	{
                	$total_size = intval($doc_);
                	hd_print(" size = $total_size");
			if($free_space >= $total_size)
			{
				$this->disk_space = 1;
			}
			else
			{
				hd_print("low disk space");
				$this->disk_space = 0;
			}
            	}*/
	}
		public function load_radio_list()
		{
			$doc = HD::http_get_document("http://file-teleport.com/iptv/api/v1/xml/get_list_radio?sid=".$this->cookie);
			hd_print("--->>> get_list_radio: $doc");
			$xml = simplexml_load_string($doc);

        		if ($xml === false)
        		{
         		   hd_print("Error: can not parse XML document.");
         		   hd_print("XML-text: $doc.");
         		   throw new Exception('Illegal XML document');
        		}

        		if ($xml->getName() !== 'response')
        		{
        		    hd_print("Error: unexpected node '" . $xml->getName() . "'. Expected: 'response'");
        		    throw new Exception('Invalid XML document');
        		}
			return $xml;
		}
///////////////////////////////////////////////////////////////////////////
	public function get_channel_list($plugin_cookies)
		{
		if (isset($plugin_cookies->time_shift))
		 $time_shift = '&time_shift='.$plugin_cookies->time_shift;
		 else
		 $time_shift = '';
			$doc = HD::http_get_document(self::API_URL."get_channels_tv?sid=".$this->cookie.$time_shift);
			//hd_print("--->>> get_list_tv: $doc");
			$xml = simplexml_load_string($doc);

        		if ($xml === false)
        		{
         		   hd_print("Error: can not parse XML document.");
         		   hd_print("XML-text: $doc.");
         		   throw new Exception('Illegal XML document');
        		}

        		if ($xml->getName() !== 'response')
        		{
        		    hd_print("Error: unexpected node '" . $xml->getName() . "'. Expected: 'response'");
        		    throw new Exception('Invalid XML document');
        		}
			return $xml;	
		}
	public function get_group_tv()
	{
		$doc = HD::http_get_document(self::API_URL.'get_groups_tv?sid='.$this->cookie);
		hd_print("--->>> get_group_list: $doc");
		try
		{
			$data = simplexml_load_string($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_group_list failed.', true);
		}
		return $data;	
	}
///////////////////////////////////////////////////////////////////////////
	public function get_rodnoe_epg($day_start,$channel_id,$sid, &$plugin_cookies)
		{
		if (isset($plugin_cookies->time_shift)) {
			if ($plugin_cookies->time_shift != 0) {
			$time_shift = '&time_shift='.$plugin_cookies->time_shift;
			hd_print("time-shift--->$time_shift");
		}
				else 
				$time_shift = '';
		}
		else 
		$time_shift = '';
			$doc = HD::http_get_document(self::API_URL."get_epg?sid=".$this->cookie."&cid=".$channel_id."&from_uts=".$day_start."&hours=24".$time_shift);
			hd_print("--->>> epg: $doc");
       	 		if (is_null($doc))
            			throw new Exception('Can not fetch epg');
     
        		$xml = simplexml_load_string($doc);

        		if ($xml === false)
        		{
            			hd_print("Error: can not parse XML document.");
            			hd_print( "XML-text: $doc.");
            			throw new Exception('Illegal XML document');
        		}

        		if ($xml->getName() !== 'response')
        		{
            			hd_print("Error: unexpected node '" . $xml->getName() . "'. Expected: 'response'");
            			throw new Exception('Invalid XML document');
        		}

        		if ($xml->channels->getName() !== 'channels')
        		{
            			hd_print("Error: unexpected node '" . $xml->channels->getName() . "'. Expected: 'channels'");
            			throw new Exception('Invalid XML document');
        		}
			return $xml;

		}
///////////////////////////////////////////////////////////////////////////
	public function get_url($cid,$gmt,$protect_code,&$plugin_cookies)
	{
		//RUB 18.05.2013
		//добавили with_ts=1
		$epg_shift = isset($plugin_cookies->epg_shift) ? $plugin_cookies->epg_shift : '0';
		//$cid = $cid - $epg_shift;
		$time_shift = isset($plugin_cookies->time_shift) ? $plugin_cookies->time_shift : 0;
		if ($time_shift != 0) {
			$time_shift = '&time_shift='.$plugin_cookies->time_shift;
		}
		else 
		$time_shift = '';
		if (preg_match('/radio_/i', $cid)) {
		$cid = str_replace('radio_', '', $cid);
		$doc=self::API_URL."get_url_radio?sid=".$this->cookie."&cid=$cid".$time_shift;
		$doc = HD::http_get_document($doc);
		$data = simplexml_load_string($doc);
		$url = urldecode(strval($data->url));
		}
		else {
        if (!isset($protect_code))
        			{
	 	  			hd_print("---> not protected:$protect_code");
         	  		$doc=self::API_URL."get_url_tv?sid=".$this->cookie."&cid=$cid".$time_shift;
        			}
        			else 
        			{
	 	  			hd_print("---> protected::$protect_code");
	 	  			$doc = self::API_URL."get_url_tv?sid=".$this->cookie."&cid=$cid".$time_shift."&protect_code=$protect_code";         
        			}
					
		if($gmt >= 0)
		{
		hd_print("gmt--->$gmt");
			$doc .= "&uts=$gmt";
		}
		$doc = HD::http_get_document($doc);
		hd_print("--->>> get_url: $doc");
		
		try
		{
			$data = simplexml_load_string($doc);
					$url = $data->url;
					$url = str_ireplace("http://","http://ts://",$url);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_url failed.', true);
		}
			if (isset($data->error)) {
			if ($data->error->message == 'Ошибочный родительский пароль') {
			hd_print("Ошибочный родительский пароль");
			
			$url = 'http://portal.ozo.tv/dunehd/wrong_pass.png';
			}
			}

		}
		hd_print("url ----> $url");
		return $url;	
	}

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

	public function get_vod_genres()
	{
		$doc = HD::http_get_document(self::API_URL.'get_genre_movie?sid='.$this->cookie);
		//hd_print("--->>> get_vod_genres: $doc");
		try
		{
			$data = simplexml_load_string($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_genres failed.', false);
		}				
		return $data;	
	}

///////////////////////////////////////////////////////////////////////////
//TODO 2
	public function get_vod_list($aid,$bid,$page)
	{
		if($aid == 'search')
		{
			$bid = urlencode($bid);
			$doc = HD::http_get_document(self::API_URL.'get_list_movie?sid='.$this->cookie.'&word='.$bid.'&limit=100&page='.$page);
		}
		elseif($aid == 'all')
		{
			$doc = HD::http_get_document(self::API_URL.'get_list_movie?sid='.$this->cookie.'&limit=100&page='.$page);
		}
		else
		{
			$doc = HD::http_get_document(self::API_URL.'get_list_movie?sid='.$this->cookie.'&genre='.$bid.'&limit=100&page='.$page);
		}

		//hd_print("--->>> get_vod_list: $doc");
		try
		{
			$data = simplexml_load_string($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}				
		return $data;	
	}

///////////////////////////////////////////////////////////////////////////
	public function get_vod_info($id)
	{
		$doc = self::API_URL.'get_list_movie?sid='.$this->cookie.'&idlist='.$id.'&extended=1';
		hd_print("--->>> get_vod_info: $doc");
		try
		{
			$data = simplexml_load_file($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}				
		return $data;	
			
	}

///////////////////////////////////////////////////////////////////////////
	public function get_vod_url($fileid)
	{
		$doc = self::API_URL.'get_url_movie?cid='.$fileid.'&sid='.$this->cookie; 
		hd_print("--->>> get_vod_url: $doc");
		try
		{
			$data = simplexml_load_file($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,'get_vod_list failed.', false);
		}				
		return $data;	
	}

///////////////////////////////////////////////////////////////////////////
//TODO 3
	public function set_settings($control_id, $new_value)
	{
		if($control_id == 'pcode')
		{
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.$new_value);
		}
		else if($control_id == 'timeshift')
		{
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.$new_value);
		}
		else
		{
			$doc = self::API_URL.'settings_set.php?var='.$control_id.'&val='.$new_value;
		}
		hd_print("--->>> set_settings: $doc");
		try
		{
			$data = simplexml_load_string($doc);
		}
		catch (Exception $e)
		{
			throw $this->api_exception($e,"get settings $control_id failed.", false);
		}
		

		if (!isset($data->error))
		{	if($control_id != 'pcode')
			hd_print("sapis");
			 $this->settings->{$control_id}->value = $new_value;
		}
		else
		{
			throw new MyPlugIN_Exception($data->error->message, $code,false);
		}
	
	}
	public function set_set_pro($control_id, $new_value)
	{
	hd_print("---$new_value");
	if($control_id == 'timeshift')
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.'&var=time_shift&val='.strval($new_value));
	
	if($control_id == 'stream_server')
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.'&var=media_server_id&val='.strval($new_value));
	if($control_id == 'epg_shift')
			$doc = HD::http_get_document(self::API_URL.'set?sid='.$this->cookie.'&var=time_zone&val='.strval($new_value));
	}

///////////////////////////////////////////////////////////////////////////
//TODO 4
	public function set_channels_order($id,$act)
	{
		if($id == -1)
		{
			$doc = self::API_URL.'set_channels_order.php?act='.$act;
		}
		else
		{
			$doc = self::API_URL.'set_channels_order.php?id='.$id.'&act='.$act;
		}
		hd_print("--->>> set_channels_order: $doc");
		$data = $this->json_fetch($doc,0);
		if (intval($data->message->code) == 4)
		{	
			return $data;
		}
		else
		{
			throw new MyPlugIN_Exception($data->error->message, $code);
		}

	}

///////////////////////////////////////////////////////////////////////////
	public function get_channels_order()
	{
		$doc = self::API_URL.'get_channels_oder.php';
		hd_print("--->>> get_channels_order: $doc");
		$data = $this->json_fetch($doc,0);
		return $data;	
	}

///////////////////////////////////////////////////////////////////////////
	public function json_fetch($url,$islogin)
	{
		if($islogin == 0)
		{
			if (strpos($url,"?") === false )
			{
		    		$url .= "?$this->cookie";
			}
			else
			{
		    		$url .= "&$this->cookie";
			}
		}
		$doc = HD::http_get_document($url);
		#hd_print("--->>> get_json: $doc");
		$data = simplexml_load_string($doc);
		hd_print("--->>> get_xml: $doc");
		if ($data === null)
                throw new Exception('Invalid data received from server');
		if (isset($data->error))
            	{
			$code = intval($data->error->code);
			hd_print("API error: URL '$url' " .
                    	"returned error with code=$code, msg=" .
                    	$data->error->message . '.');
			throw new MyPlugIN_Exception($data->error->message, $code);
		}
		return $data;
	}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
    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_close_dialog_button($defs,
            		'Отменить', 300);

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

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

	} 
///////////////////////////////////////////////////////////////////////////
    public function apply_sub(&$plugin_cookies, &$user_input)
    {
        if (!isset($user_input->control_id) ||
            $user_input->control_id != 'apply_sub')
        {
	    #hd_print("dalshe: $user_input->control_id");
            return false;
	}
	if ($user_input->control_id == 'close')
        {
		hd_print("close");
		return array(
               'need_close_dialog' => true,
                'action' =>ActionFactory::close_dialog());
        }


        if ($user_input->login === '' || $user_input->pass === '')
        {
		return array(
                'need_close_dialog' => false,
                'action' =>ActionFactory::show_error(false,'Error',array('Поле Логин не может быть пустым.')));
        }

	$plugin_cookies->login = $user_input->login;
	$plugin_cookies->pass = $user_input->pass;
	$islogged = $this->is_logged_in();
	if ($islogged == true)
	{
        	$this->logout();
	}
        $post_action = null;
        try
        {
            $this->login_mylogin($plugin_cookies);
        }
        catch (DuneException $e)
        {
            $post_action = $e->get_error_action();
        }
		
	if ($this->is_logged == false)
	{
	hd_print("--------------------");
		return array(
                'need_close_dialog' => false,
                'action' =>ActionFactory::show_error(false,'Error',array('Неправильный логин или пароль')));
	}
        return array(
            'need_close_dialog' => true,
            'action' => $post_action);
    }
///////////////////////////////////////////////////////////////////////////
    public function get_archive()
    {
	if ($this->disk_space == 100)
	{
        	return DefaultArchive::get_archive('ico', MyPlugIN_Config::ARCHIVE_URL);
	}
	else
	{
		return null;
	}
    }

    public function get_icon($icon)
    {
        #hd_print("disk_space:$this->disk_space");
	if ($this->disk_space == 1)
	{
        	$archive = DefaultArchive::get_archive('ico',MyPlugIN_Config::ARCHIVE_URL); 
        	return $archive->get_archive_url($icon);
	}
	else
	{
		$icon_url = $icon;
		#hd_print("eee:$icon_url");
		return $icon_url;
	} 
 
    }	


}
