<?php

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

class Yealink_t4x extends AbstractPhoneModel
{

    public function __construct($manufactorName = "Yealink", $phoneModelName = "", $phoneUserAgent = "")
    {
        $this->mManufactorName = $manufactorName;
        $this->mPhoneModelName = $phoneModelName;
        $this->mPhoneUserAgent = $phoneUserAgent;
    }

    public static function getManufactorName()
    {
        return "Yealink";
    }

    public static function getFunctionPlaceholders()
    {
        return array(
            'no' => 'PHONE_TIPTEL_FUNCTION_NOT_OVERRIDE',
            '0' => 'PHONE_TIPTEL_FUNCTION_EMPTY',
            '3' => 'PHONE_TIPTEL_FUNCTION_TRANSFER', // Transfer
            '4' => 'PHONE_TIPTEL_FUNCTION_HOLD', // Hold
            '5' => 'PHONE_TIPTEL_FUNCTION_DND', # DND
            '7' => 'PHONE_TIPTEL_FUNCTION_REDIAL', // Redial
            '12' => 'PHONE_TIPTEL_FUNCTION_VOICEMAIL', # Voicemail
            '13' => 'PHONE_TIPTEL_FUNCTION_SPEEDDIAL', // SpeedDial
            '14' => 'PHONE_TIPTEL_FUNCTION_INTERCOM', # Intercom
            '15' => 'PHONE_TIPTEL_FUNCTION_LINE', // Line (for line key only)
            '16' => 'PHONE_TIPTEL_FUNCTION_BUSY_LAMP_FIELD', // BLF
            '17' => 'PHONE_TIPTEL_FUNCTION_URL', // URL
            '25' => 'PHONE_TIPTEL_FUNCTION_RECORD', // Record
            'X01' => 'PHONE_TIPTEL_FUNCTION_FORWARD', //Call Forward
            'X02' => 'PHONE_TIPTEL_FUNCTION_NIGHT_CIRCUT', // Night Circuit
            'X03' => 'PHONE_TIPTEL_FUNCTION_QUEUE_LOGIN', // Queue Login/Logout
            'X04' => 'PHONE_TIPTEL_FUNCTION_SPEEDDIAL_PHONALISA', // SpeedDial
            'X06' => 'PHONE_TIPTEL_FUNCTION_CALL_PICKUP', // Direct Pickup
            'X09' => 'PHONE_TIPTEL_FUNCTION_LISTENING', // Group Listening
            'X10' => 'PHONE_TIPTEL_FUNCTION_ALL_QUEUES_LOGOUT', // Logout from all Queues
            'X11' => 'PHONE_TIPTEL_FUNCTION_HOT_DESKING', // Hot Desking
            'X12' => 'PHONE_TIPTEL_FUNCTION_ALL_QUEUES_LOGIN', // Login to all Queues
            'X13' => 'PHONE_TIPTEL_FUNCTION_CALLGROUP_LOGIN', // Call Group Login/Logout
        );
    }

    public function validateFirmwareFile($filename, $fileTmpPath, &$errorText)
    {
        // Filename ist like: 7.71.0.125.rom

        if ($filename == "") {
            $errorText = __("FIRMWARE_VALIDATION_ERROR_FILE_NOT_SET");
            return false;
        }

        $errorText = __("FIRMWARE_VALIDATION_ERROR_WRONG_FILE_IS_NOT_VALID");
        // check filename
        if (!$this->endsWith($filename, ".rom")) {
            return false;
        }

        $filename = substr($filename, 0, strlen($filename) - 4);
        $parts = explode(".", $filename);
        //$errorText = print_r($parts, true);

        if (count($parts) != 4) {
            return false;
        }

        $versionMatchesForPhone = false;
        if ($parts[0] == "28" && $this->mPhoneModelName == "yealink-t46g") {
            $versionMatchesForPhone = true;
        } else if ($parts[0] == "29" && $this->mPhoneModelName == "yealink-t42g") {
            $versionMatchesForPhone = true;
        } else if ($parts[0] == "35" && $this->mPhoneModelName == "yealink-t48g") {
            $versionMatchesForPhone = true;
        } else if ($parts[0] == "44" && $this->mPhoneModelName == "yealink-t23p") {
            $versionMatchesForPhone = true;
        } else if ($parts[0] == "58" && $this->mPhoneModelName == "yealink-t58") {
            $versionMatchesForPhone = true;
        } else if ($parts[0] == "73" && $this->mPhoneModelName == "yealink-cp960") {
            $versionMatchesForPhone = true;
        } else if ($parts[0] == "66") {
            $validPhonesFor66 = array();
            $validPhonesFor66[] = "yealink-t48s";
            $validPhonesFor66[] = "yealink-t46s";
            $validPhonesFor66[] = "yealink-t42s";
            $validPhonesFor66[] = "yealink-t41s";
            if (in_array($this->mPhoneModelName, $validPhonesFor66)) {
                $versionMatchesForPhone = true;
            }
        }

        if (!$versionMatchesForPhone) {
            $errorText = __("FIRMWARE_VALIDATION_ERROR_WRONG_FILE_IS_NOT_A_FIRMWARE_FOR") . ": " . $this->mPhoneModelNameHuman;
            return false;
        }

        $vParts = $parts;
        $vPartsNormal = array();
        $vPartsNormal[] = str_pad($vParts[0], 2, '0', STR_PAD_LEFT);
        $vPartsNormal[] = str_pad($vParts[1], 2, '0', STR_PAD_LEFT);
        $vPartsNormal[] = str_pad($vParts[2], 2, '0', STR_PAD_LEFT);
        $vPartsNormal[] = str_pad($vParts[3], 3, '0', STR_PAD_LEFT);
        $firmwareVersion = implode(".", $vPartsNormal);

        return $firmwareVersion;
    }

    public static function getFunctions($translated = true)
    {
        if ($translated) {
            $functions = array();
            foreach (self::getFunctionPlaceholders() as $key => $value) {
                $functions[$key] = __($value);
            }
            return $functions;
        } else {
            return self::getFunctionPlaceholders();
        }
    }

    public function getAvailableKeys($level)
    {
        $phones = $this->getSupportedPhoneModels();
        if (!array_key_exists($this->mPhoneModelName, $phones)) {
            return array();
        }

        $phone = $phones[$this->mPhoneModelName];
        $ret = array();

        if ($level == "" || $level == "memory") {
            for ($i = 1; $i <= $phone->getKeys(); $i++) {
                $button = new PhoneKey();
                $button->name = 'memory' . $i;
                $button->phone = $this->mPhoneModelName;
                $button->function = '';
                $button->level = 'memory';
                $button->key_idx = $i;
                $button->availableFunctions = $this->getFunctions(true, $button->phone, $button->level);
                $ret[$button->name] = $button;
            }
        }

        if ($level == "" || $level == "line") {
            for ($i = 1; $i <= $phone->getLineKeys(); $i++) {
                $button = new PhoneKey();
                $button->name = "linekey." . $i;
                $button->phone = $this->mPhoneModelName;
                $button->function = '';
                $button->key_idx = $i;
                $button->level = 'line';
                $button->availableFunctions = $this->getFunctions();
                $ret[$button->name] = $button;
            }
        }

        if (startsWith($level, "expansion")) {
            for ($i = 1; $i <= $phone->getExtKeys(); $i++) {
                $button = new PhoneKey();
                $button->name = $level . ".key." . $i;
                $button->phone = $this->mPhoneModelName;
                $button->function = '';
                $button->key_idx = $level . ".key." . $i;
                $button->level = $level;
                $button->availableFunctions = $this->getFunctions();
                $ret[$button->name] = $button;
            }
        }
        return $ret;
    }

    public function getAvailableKeyLevels()
    {
        $phones = $this->getSupportedPhoneModels();
        if (!array_key_exists($this->mPhoneModelName, $phones)) {
            return array();
        }
        $phone = $phones[$this->mPhoneModelName];

        $keyLevels = array();

        if ($phone->getLineKeys() != 0) {
            $lineKeyLevel = array();
            $lineKeyLevel["level"] = "line";
            $lineKeyLevel["name"] = "TIPTEL_KEYLEVEL_LINE_KEYS_NAME";
            $lineKeyLevel["descr"] = "TIPTEL_KEYLEVEL_LINE_KEYS_DESCR";
            $keyLevels[] = $lineKeyLevel;
        }

        if ($phone->getKeys() != 0) {
            $memoryKeyLevel = array();
            $memoryKeyLevel["level"] = "memory";
            $memoryKeyLevel["name"] = "TIPTEL_KEYLEVEL_MEMORY_KEYS_NAME";
            $memoryKeyLevel["descr"] = "TIPTEL_KEYLEVEL_MEMORY_KEYS_DESCR";
            $keyLevels[] = $memoryKeyLevel;
        }

        if ($phone->getExtKeys() != 0) {
            for ($i = 1; $i <= $phone->getExtModules(); $i++) {
                $keyLevel = array();
                $keyLevel["level"] = "expansion_module." . $i;
                $keyLevel["name"] = "TIPTEL_KEYLEVEL_EXPANSION_KEYS_NAME";
                $keyLevel["descr"] = "TIPTEL_KEYLEVEL_EXPANSION_KEYS_DESCR";
                $keyLevels[] = $keyLevel;
            }
        }
        return $keyLevels;
    }

    public static function getSupportedPhoneModels()
    {
        $models = array();

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t23p", "sip-t23p");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T23P");
        $tmp->setKeys(0);
        $tmp->setLineKeys(3);
        $tmp->setExtKeys(0);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t41g", "sip-t41g");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T41G");
        $tmp->setKeys(0);
        $tmp->setLineKeys(6);
        $tmp->setExtKeys(0);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t42g", "sip-t42g");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T42G");
        $tmp->setKeys(0);
        $tmp->setLineKeys(12);
        $tmp->setExtKeys(0);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t46g", "sip-t46g");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T46G");
        $tmp->setKeys(0);
        $tmp->setLineKeys(27);
        $tmp->setExtKeys(40);
        $tmp->setExtModules(3);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t48g", "sip-t48g");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T48G");
        $tmp->setKeys(0);
        $tmp->setLineKeys(29);
        $tmp->setExtKeys(40);
        $tmp->setExtModules(3);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t41s", "sip-t41s");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T41S");
        $tmp->setKeys(0);
        $tmp->setLineKeys(6);
        $tmp->setExtKeys(0);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t42s", "sip-t42s");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T42S");
        $tmp->setKeys(0);
        $tmp->setLineKeys(12);
        $tmp->setExtKeys(0);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t46s", "sip-t46s");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T46S");
        $tmp->setKeys(0);
        $tmp->setLineKeys(27);
        $tmp->setExtKeys(40);
        $tmp->setExtModules(3);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t48s", "sip-t48s");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T48S");
        $tmp->setKeys(0);
        $tmp->setLineKeys(29);
        $tmp->setExtKeys(40);
        $tmp->setExtModules(3);
        $models[$tmp->getPhoneModelName()] = $tmp;


        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t56", "sip-t56");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T56");
        $tmp->setKeys(0);
        $tmp->setLineKeys(28);
        $tmp->setExtKeys(60);
        $tmp->setExtModules(3);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-t58", "sip-t58");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-T58");
        $tmp->setKeys(0);
        $tmp->setLineKeys(28);
        $tmp->setExtKeys(60);
        $tmp->setExtModules(3);
        $models[$tmp->getPhoneModelName()] = $tmp;

        $tmp = new Yealink_t4x(Yealink_t4x::getManufactorName(), "yealink-cp960", "sip-cp960");
        $tmp->setPhoneModelNameHumanReadable("Yealink SIP-CP960");
        $tmp->setKeys(0);
        $tmp->setLineKeys(30);
        $tmp->setExtKeys(0);
        $tmp->setExtModules(0);
        $models[$tmp->getPhoneModelName()] = $tmp;

        return $models;
    }

    public function phoneDoesSupportURLDial($phone)
    {
        $result = false;
        if (startsWith($phone->getManufactor(), $this->getManufactorName())) {
            $result = true;
        }
        return $result;
    }

    public function getCallServiceURL($to, $id, $clip)
    {
        $protocol = cfg('PROV_PROTOCOL');
        $host = cfg('PROV_HOST');
        $sipAccount = SipAccounts::model()->findByAttributes(array('user_id' => $id, 'state' => 'online'));
        $userPhoneIP = $sipAccount->current_ip;
        $userPhoneNumber = $sipAccount->authname;
        if ($clip != '') {
            $userPhoneNumber = $clip;
        }
        $url = $protocol . "admin:admin@$userPhoneIP/servlet?number=$to&outgoing_uri=$userPhoneNumber@$host";
        return $url;
    }
}
