<?php

require_once dirname(__FILE__).'/../../lib/phoneprovisioning.php';

class TiptelPhoneModel extends AbstractPhoneModel {

	private $mLineKeys = 0;
	private $mKeys = 0;

	public function setLineKeys($keys) {
		$this->mLineKeys = $keys;
	}

	public function setKeys($keys) {
		$this->mKeys = $keys;
	}

	public function  getLineKeys() {
		return $this->mLineKeys;
	}

	public function  getKeys() {
		return $this->mKeys;
	}


}


class TiptelPhoneProvisioning extends VirtualPhoneProvisioningController {

	protected function checkMacAddress($mac) {

		return parent::checkMacAddress($mac);
	}

	protected function checkUserAgent($ua) {
		$ua = 	"Yealink SIP-T38G 38.0.0.80 00:15:65:26:85:9f";
		//Tiptel IP Serie...
		$ua = str_replace("  ", " ", $ua);
		$ua_parts = explode(' ', $ua);
		if (strToLower(@$ua_parts[0]) === 'tiptel') {
			$found = false;
			if (strToLower(@$ua_parts[1]) === 'ip') {
				$ua_model = strToLower(@$ua_parts[2]);

				foreach($this->_getSupportedPhoneModels() as $model) {
					if ($model->getUserAgent() == $ua_model) {
						$this->setCurrentPhoneModel($model);
						$found = true;
						break;
					}
				}
			}

			# find out the firmware version of the phone
			$fw_vers = (preg_match('/(\d+\.\d+\.\d+\.\d+)/', @$ua_parts[3], $m))
			? $m[1] : '0.0.0.0';
			$fw_vers_nrml = $this->tiptel_normalize_version( $fw_vers );
			$this->setCurrentFirmwareVersion($fw_vers_nrml);
			return $found;
		}

		// Yealink VP-2009
		//VideoPhone 23.40.0.20 00:15:65:22:5c:19
		if (strToLower(@$ua_parts[0]) === 'videophone') {

			$this->Log(GS_LOG_DEBUG, "User Agent is $ua" );
			$found = false;
			foreach($this->_getSupportedPhoneModels() as $model) {
				if ($model->getUserAgent() == "VP-2009") {
					$this->setCurrentPhoneModel($model);
					$found = true;
					break;
				}
			}

			# find out the firmware version of the phone
			$fw_vers = (preg_match('/(\d+\.\d+\.\d+\.\d+)/', @$ua_parts[2], $m)) ?  $m[1] : '0.0.0.0';
			$fw_vers_nrml = $this->tiptel_normalize_version( $fw_vers );
			$this->setCurrentFirmwareVersion($fw_vers_nrml);

			return $found;

		}

		//Add Yealink processing here...
		//yealink SIP-T22P
		if (strToLower(@$ua_parts[0]) === 'yealink') {

			$found = false;
			if (substr(strToLower(@$ua_parts[1]),0,3) === 'sip') {
				$ua_model = strToLower(@$ua_parts[1]);

				foreach($this->_getSupportedPhoneModels() as $model) {
					if ($model->getUserAgent() == $ua_model) {
						$this->setCurrentPhoneModel($model);
						$found = true;
						break;
					}
				}
			}

			# find out the firmware version of the phone
			$fw_vers = (preg_match('/(\d+\.\d+\.\d+\.\d+)/', @$ua_parts[2], $m))
			? $m[1] : '0.0.0.0';
			$fw_vers_nrml = $this->tiptel_normalize_version( $fw_vers );
			$this->setCurrentFirmwareVersion($fw_vers_nrml);
			return $found;

		}

		return parent::checkUserAgent($ua);
	}


    protected function loadConfigValues($mac = NULL) {
        
        $template = $this->getTemplate();
                
        $Phone = $this->getPhoneModel();
        $SipAccount = $Phone->getSipAccount();
                
        // New Settings format
        foreach ($template as $configfile => $values) {
            //generate psetting
            foreach($values as $key => $value) {
                $this->psetting($configfile.'|'.$key, $value);
            }
        }
    
        $sipaccountcfg = "cfg:/phone/config/voip/sipAccount0.cfg,account=0;reboot=0";
        $systemcfg = "cfg:/config/system.ini,reboot=1";
        $userini = "cfg:/phone/config/user.ini,reboot=0";
        if($this->mCurrentPhoneModel->getPhoneModelName() == "yealink-vp-2009") {
            $sipaccountcfg = "cfg:/rundata/config/user/voip/sipAccount0.cfg,reboot=1";
            $systemcfg = "cfg:/rundata/config/system.ini,reboot=1";
        }
        if($this->mCurrentPhoneModel->getPhoneModelName() == "tiptel-vp28") {
            $sipaccountcfg = "cfg:/rundata/config/user/voip/sipAccount0.cfg,reboot=1";
            $systemcfg = "cfg:/rundata/config/system.ini,reboot=1";
        }
    
        $this->psetting($sipaccountcfg.'|account.SIPServerHost', $SipAccount->getSIPRegistrar());
        $this->psetting($sipaccountcfg.'|account.SIPServerPort', cfg("INTERNAL_SIP_PORT"));
        $this->psetting($sipaccountcfg.'|account.UserName', $SipAccount->authname);
        $this->psetting($sipaccountcfg.'|account.AuthName', $SipAccount->authname);
        $this->psetting($sipaccountcfg.'|account.password', $SipAccount->secret);
        $this->psetting($sipaccountcfg.'|account.Label', $SipAccount->getLabel());
        $this->psetting($sipaccountcfg.'|account.DisplayName', $SipAccount->getDisplayName());
    
        if($this->mCurrentPhoneModel->getPhoneModelName() == "tiptel-vp28") {
            $this->psetting($systemcfg.'|LocalTime.bNTPEnable', '1' );
            //FIXME $this->psetting($systemcfg.'|LocalTime.strPrimaryNTPServer', gs_get_conf('GS_TIPTEL_PROV_NTP') );        # NTP Server 1
        }
        else
        {
            //FIXME $this->psetting($systemcfg.'|LocalTime.TimeServer1', gs_get_conf('GS_TIPTEL_PROV_NTP') );        # NTP Server 1
        }
        $this->psetting($systemcfg.'|AutoProvision.strServerURL', $this->getProvURL());
    
        //FIXME $this->psetting($userini.'|Features.Call_Waiting',($this->getCallWaitingActive() ? '1' : '0'));
    
        //FIXME $this->processPhonebooks();
            
        //FIXME $softkeys = $this->getSoftKeys();
        //FIXME if ($softkeys != null) {
        //FIXME	$this->processSoftKeys($softkeys);
        //FIXME }
                                
        
        return true;

    }

	protected function generateOutput() {
		foreach ($this->mCurrentSettings as $section_name => $section_values) {
			Yii::log('[ '.$section_name.' ]', "error", "provisioning" );
			echo '[ ', $section_name, ' ]', "\n";
			foreach ($section_values as $name => $val) {		
				Yii::log( $name .' = '. $val, "error", "provisioning" );
				echo $name .' = '. $val, "\n";
			}
			echo "\n";
		}
		return false;
	}


	protected function _getSupportedPhoneModels() {
		$models = array();


		$models[] = new TiptelPhoneModel($this->getManufactorName(), "tiptel-ip386",  "386");
		$tmp->setKeys(10);
		$tmp->setLineKeys(6);
		$models[] = $tmp;



		// "Yealink SIP-T38G 38.0.0.80 00:15:65:26:85:9f"
		$models[] = new TiptelPhoneModel($this->getManufactorName(), "yealink-sip-t38g", "sip-t38g");
		$tmp->setKeys(10);
		$tmp->setLineKeys(6);
		$models[] = $tmp;

		// "Yealink SIP-T32G  32.0.0.106 00:15:65:2a:33:c4"
		$models[] = new TiptelPhoneModel($this->getManufactorName(), "yealink-sip-t32g", "sip-t32g");
		$tmp->setKeys(10);
		$tmp->setLineKeys(6);
		$models[] = $tmp;


		

		return $models;

	}

	private function tiptel_normalize_version( $fwvers )
	{
		$tmp = explode('.', $fwvers);
		$v0  = str_pad((int)@$tmp[0], 2, '0', STR_PAD_LEFT);
		$v1  = str_pad((int)@$tmp[1], 2, '0', STR_PAD_LEFT);
		$v2  = str_pad((int)@$tmp[2], 2, '0', STR_PAD_LEFT);
		$v3  = str_pad((int)@$tmp[3], 2, '0', STR_PAD_LEFT);
		return $v0.'.'.$v1.'.'.$v2.'.'.$v3;
	}

	
	private function getTemplate() {
	
		$contents = file_get_contents( dirname(__FILE__)."/templates/".$this->mCurrentPhoneModel->getPhoneModelName().".tpl" );
	
		$contents = explode("\n", $contents);
		$config = array();
		$currentsection = "";
		foreach($contents as $line) {
	
			$line = trim($line);
	
			if (strlen($line) == 0) {
				continue;
			}
	
			if($line[0] == "#") {
				continue;
			}
	
			if($line[0] == ";") {
				continue;
			}
	
	
			if ($line[0] == "[") {
				$currentsection = $line;
				$currentsection = trim($currentsection, "][ ");
				continue;
			}
	
			$parts = explode("=", $line);
	
			$key = trim($parts[0]);
			$value = trim(@$parts[1]);
	
			$config[$currentsection][$key] = $value;
	
		}
		return $config;
	
	}
	
	protected  function psetting($sectionname, $val='') {
		if ( strPos($sectionname,'|') ) {
			list($section, $name) = explode('|', $sectionname);
			if ( $section !== '' && $name !== '' ) {
				if (! array_key_exists($section, $this->mCurrentSettings)
				|| ! is_array($this->mCurrentSettings[$section]) ) {
					$this->mCurrentSettings[$section] = array();
				}
				$this->mCurrentSettings[$section][$name] = $val;
			}
		}
	}
	
	

}














