<?php

/**
 * This is the model class for table "gateway".
 *
 * The followings are the available columns in table 'gateway':
 * @property integer $id
 * @property string $name
 * @property string $host
 * @property string $authname
 * @property string $secret
 * @property string $current_ip
 * @property string $device_name
 * @property integer $expires
 * @property string $typ
 * @property string $state
 * @property string $inc_called_field
 * @property string $inc_called_search
 * @property string $inc_called_replace
 */

class T38Mode {
    const NONE = "";
    const SELF = "self";
    const PEER = "peer";
    const PASSTHROUGH = "passthrough";
    
    public static function getHumanReadable($t38Mode, $translated = true) {
        if ($t38Mode == T38Mode::NONE) {
            return $translated === true ? __("GATEWAY_MODEL_T_38_MODE_NONE") : "GATEWAY_MODEL_T_38_MODE_NONE";
        } else if ($t38Mode == T38Mode::SELF) {
            return $translated === true ? __("GATEWAY_MODEL_T_38_MODE_SELF") : "GATEWAY_MODEL_T_38_MODE_SELF";
        } else if ($t38Mode == T38Mode::PEER) {
            return $translated === true ? __("GATEWAY_MODEL_T_38_MODE_PEER") : "GATEWAY_MODEL_T_38_MODE_PEER";
        } else if ($t38Mode == T38Mode::PASSTHROUGH) {
            return $translated === true ? __("GATEWAY_MODEL_T_38_MODE_PASSTHROUGH") : "GATEWAY_MODEL_T_38_MODE_PASSTHROUGH";
        }
        return "unknown";
    }
}

class CIDType {
    const NONE = "none";
    const RPID = "rpid";
    const PID = "pid";

    public static function getHumanReadable($type, $translated = true) {
        if ($type == CIDType::NONE) {
            return $translated === true ? __("GATEWAY_MODEL_CID_TYPE_NONE") : "GATEWAY_MODEL_CID_TYPE_NONE";
        } else if ($type == CIDType::RPID) {
            return $translated === true ? __("GATEWAY_MODEL_CID_TYPE_REMOTE_PARTY_ID") : "GATEWAY_MODEL_CID_TYPE_REMOTE_PARTY_ID";
        } else if ($type == CIDType::PID) {
            return $translated === true ? __("GATEWAY_MODEL_CID_TYPE_P_ASSERTED_IDENTITY") : "GATEWAY_MODEL_CID_TYPE_P_ASSERTED_IDENTITY";
        }
        return "????";
    }
}

class NumberFormat {
    
    const None = 0;
    const E164WithPlus = 1;
    const E164WithDoubleNull = 2;
    const E164WithoutNullAndPlus = 3;
    const LikeOutboundSetting = 4;
    
    public static function getHumanReadable($numberFormat, $translated = true) {
        if ($numberFormat == self::None) {
            return $translated === true ? __("GATEWAY_MODEL_NUMBER_FORMAT_NONE") : "GATEWAY_MODEL_NUMBER_FORMAT_NONE";
        } else if ($numberFormat == self::E164WithPlus) {
            return $translated === true ? __("GATEWAY_MODEL_NUMBER_FORMAT_E164_WITH_PLUS") : "GATEWAY_MODEL_NUMBER_FORMAT_E164_WITH_PLUS";
        } else if ($numberFormat == self::E164WithDoubleNull) {
            return $translated === true ? __("GATEWAY_MODEL_NUMBER_FORMAT_E164_WITH_DOUBLE_NULL") : "GATEWAY_MODEL_NUMBER_FORMAT_E164_WITH_DOUBLE_NULL";
        } else if ($numberFormat == self::E164WithoutNullAndPlus) {
            return $translated === true ? __("GATEWAY_MODEL_NUMBER_FORMAT_E164_WITHOUT_NULL_AND_PLUS") : "GATEWAY_MODEL_NUMBER_FORMAT_E164_WITHOUT_NULL_AND_PLUS";
        } else if ($numberFormat == self::LikeOutboundSetting) {
            return $translated === true ? __("GATEWAY_MODEL_NUMBER_FORMAT_LIKE_OUTBOUND_SETTING") : "GATEWAY_MODEL_NUMBER_FORMAT_LIKE_OUTBOUND_SETTING";
        }
        return "????";
    }
}

class SIPHeader {
    
    const NONE = "";
    const TO = "To";
    const CONTACT = "Contact";
    const P_CALLED_PARTY_ID = "P-Called-Party-ID";
    const FROM = "From";
    const P_ASSERTED_IDENTITY = "P-Asserted-Identity";
    const P_PREFERRED_IDENTITY ="P-Preferred-Identity";
    const REMOTE_PARTY_ID = "Remote-Party-ID";
    
    
    public static function getHumanReadable($SIPHeader, $translated = true) {
        if ($SIPHeader == self::NONE) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_NONE") : "GATEWAY_MODEL_SIP_HEADER_NONE";
        } else if ($SIPHeader == self::TO) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_TO") : "GATEWAY_MODEL_SIP_HEADER_TO";
        } else if ($SIPHeader == self::CONTACT) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_CONTACT") : "GATEWAY_MODEL_SIP_HEADER_CONTACT";
        } else if ($SIPHeader == self::P_CALLED_PARTY_ID) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_P_CALLED_PARTY_ID") : "GATEWAY_MODEL_SIP_HEADER_P_CALLED_PARTY_ID";
        } else if ($SIPHeader === self::FROM) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_FROM") : "GATEWAY_MODEL_SIP_HEADER_FROM";
        } else if ($SIPHeader === self::P_ASSERTED_IDENTITY ) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_P_ASSERTED_IDENTITY") : "GATEWAY_MODEL_SIP_HEADER_P_ASSERTED_IDENTITY";
        } else if ($SIPHeader === self::P_PREFERRED_IDENTITY) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_P_PREFERRED_IDENTITY") : "GATEWAY_MODEL_SIP_HEADER_P_PREFERRED_IDENTITY";
        } else if ($SIPHeader === self::REMOTE_PARTY_ID) {
            return $translated === true ? __("GATEWAY_MODEL_SIP_HEADER_REMOTE_PARTY_ID") : "GATEWAY_MODEL_SIP_HEADER_REMOTE_PARTY_ID";
        }
        return "????";
    }
}

class CLIRMode {

    const NotSupported = 0;
    const PrivacyHeader = 1;
    const CIDToAnon = 2;

    public static function getHumanReadable($clipMode, $translated = true) {
        if ($clipMode == self::NotSupported) {
            return $translated === true ? __("GATEWAY_MODEL_CLIR_MODE_NOT_SUPPORTED") : "GATEWAY_MODEL_CLIR_MODE_NOT_SUPPORTED";
        } else if ($clipMode == self::PrivacyHeader) {
            return $translated === true ? __("GATEWAY_MODEL_CLIR_MODE_PRIVACY_HEADER") : "GATEWAY_MODEL_CLIR_MODE_PRIVACY_HEADER";
        } else if ($clipMode == self::CIDToAnon) {
            return $translated === true ? __("GATEWAY_MODEL_CLIR_MODE_CID_TO_ANON") : "GATEWAY_MODEL_CLIR_MODE_CID_TO_ANON";
        }
        return "????";
    }
}



class Gateway extends PhonalisaRecord
{

    public $id;
    public $name;
    public $host;
    public $authname;
    public $authusername;
    public $secret;
    public $current_ip;
    public $device_name;
    public $expires;
    public $typ = "sip";
    public $state;
    public $inc_called_field;
    public $inc_called_search;
    public $inc_called_replace;
    public $maxChannels;
    
    public $inboundBlacklistId;
    public $outboundBlacklistId;
    public $inboundWhitelistId;
    public $outboundWhitelistId;
    
    public $std_prefix; // ??
    public $dialOutToggle;
    
    public $active = '1';
    public $register;
    public $answer_on_outbound_dial = '0';
    
    public $caller_id_in_from = '0';
    public $expire_seconds;
    public $realm;
    public $from_user;
    public $from_domain;
    public $proxy;
    public $register_proxy;
    public $register_transport;
    public $contact_params;
    
    public $tcp_transport;
    public $tls_transport;
    public $force_srtp;

    public $allowed_codecs;
    public $t38Mode;
    public $sip_cid_type;
    public $scriptExtension;
    
    public $ping;
    public $calldeflect_support;
    
    public $did_in_to;
    public $csvImported = '0';
    public $providerTemplate = "default";
    public $extension_in_contact;
    
    public $clip_no_screening;
    public $number_format_cid;
    public $number_format_cid_inbound;
    public $number_format_target;
    public $number_format_target_inbound;
    public $number_format_target_emergency = NumberFormat::LikeOutboundSetting;
    public $answer_on_outbound_dial_on_call_forward;
    public $unset_sip_headers;
    public $set_sip_headers;
    public $clir_mode;
    public $did_header;
    public $did_header_regex;
    public $cid_header_inbound;
    public $cid_header_regex_inbound;
    public $meta1;
    public $debug;

    public $intl_prefix;
    public $area_code;
    public $head_number;

    public $hasAdditionalData;

    public $did_from;
    public $did_to;
    public $allow_unauth_calls_from_this_host;

    public static function myAttributes()
    {
        return array(
            'name' => 'name',
            'host' => 'host',
            'maxChannels' => 'maxChannels',
            'authname' => 'authname',
            'authusername' => 'authusername',
            'secret' => 'secret',
            'current_ip' => 'current_ip',
            'device_name' => 'device_name',
            'expires' => 'expires',
            'typ' => 'typ',
            'state' => 'state',
            'inc_called_field' => 'inc_called_field',
            'inc_called_replace' => 'inc_called_replace',
            'inc_called_search' => 'inc_called_search',
            'std_prefix' => 'std_prefix',
            'dialOutToggle' => 'dialOutToggle',
            'inboundBlacklistId' => 'inboundBlacklistId',
            'outboundBlacklistId' => 'outboundBlacklistId',
            'inboundWhitelistId' => 'inboundWhitelistId',
            'outboundWhitelistId' => 'outboundWhitelistId',
            'active' => 'active',
            'register' => 'register',
            'caller_id_in_from' => 'caller_id_in_from',
            'expire_seconds' => 'expire_seconds',
            'realm' => 'realm',
            'from_user' => 'from_user',
            'from_domain' => 'from_domain',
            'proxy' => 'proxy',
            'register_proxy' => 'register_proxy',
            'register_transport' => 'register_transport',
            'tcp_transport' => 'tcp_transport',
            'tls_transport' => 'tls_transport',
            'force_srtp' => 'force_srtp',
            'allowed_codecs' => 'allowed_codecs',
            'contact_params' => 'contact_params',
            'ping' => 'ping',
            'calldeflect_support' => 'calldeflect_support',
            'answer_on_outbound_dial' => 'answer_on_outbound_dial',
            'did_in_to' => 'did_in_to',
            "t38Mode" => "t38Mode",
            "sip_cid_type" => "sip_cid_type",
            "scriptExtension" => "scriptExtension",
            'csvImported' => 'csvImported',
            'providerTemplate' => 'providerTemplate',
            'extension_in_contact' => 'extension_in_contact',
            'clip_no_screening' => 'clip_no_screening',
            'number_format_cid' => 'number_format_cid',
            'number_format_cid_inbound' => 'number_format_cid_inbound',
            'number_format_target' => 'number_format_target',
            'number_format_target_inbound' => 'number_format_target_inbound',
            'number_format_target_emergency' => 'number_format_target_emergency',
            'answer_on_outbound_dial_on_call_forward' => 'answer_on_outbound_dial_on_call_forward',
            'unset_sip_headers' => 'unset_sip_headers',
            'set_sip_headers' => 'set_sip_headers',
            'clir_mode' => 'clir_mode',
            'did_header' => 'did_header',
            'did_header_regex' => 'did_header_regex',
            'cid_header_inbound' => 'cid_header_inbound',
            'cid_header_regex_inbound' => 'cid_header_regex_inbound',
            'meta1' => 'meta1',
            'debug' => 'debug',
            "hasAdditionalData" => "hasAdditionalData",
            'allow_unauth_calls_from_this_host' => 'allow_unauth_calls_from_this_host',
            "intl_prefix" => "intl_prefix",
            "area_code" => "area_code",
            "head_number" => "head_number",
            'did_from' => 'did_from',
            'did_to' => 'did_to'
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Gateway the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'gateway';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {   
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array(implode(", ", $this->attributeNames()), 'ext.PhonalisaValidators.requiredByTemplate'),
            array('intl_prefix, area_code, head_number, expires, maxChannels, std_prefix, expire_seconds, ping,'
                . 'number_format_cid,number_format_cid_inbound, number_format_target, did_from, did_to,'
                . 'number_format_target_inbound, number_format_target_emergency',
                'numerical',
                'integerOnly' => true
                ),
            array('did_to', 'compare', 'compareAttribute' => 'did_from', 'operator' => '>='),
            array('did_to, did_from', 'numerical', 'min' => 0),
            array(
                'dialOutToggle,'
                . ' active,'
                . ' register,'
                . ' caller_id_in_from,'
                . ' tcp_transport,'
                . ' tls_transport,'
                . ' force_srtp,'
                . ' calldeflect_support,'
                . ' answer_on_outbound_dial,'
                . ' did_in_to,'
                . ' extension_in_contact,'
                . ' clip_no_screening,'
                . ' debug,'
                . 'hasAdditionalData,'
                . 'answer_on_outbound_dial_on_call_forward,'
                . 'allow_unauth_calls_from_this_host', 'boolean'),
            array('name, allowed_codecs, host, authname, secret, authusername,'
                . ' inc_called_search, inc_called_replace, realm, from_user,'
                . 'from_domain, proxy, register_proxy,'
                . 'register_transport, meta1, contact_params, unset_sip_headers, did_header, did_header_regex,',
                'length',
                'max' => 255),
            array('name', 'ext.PhonalisaValidators.isUnique'),
            array('name', 'match', 'pattern' => '/^[a-zA-Z0-9]*$/', 'message' => __('GATEWAY_MODEL_SHOULD_ONLY_CONTAIN_ALPHANUMERIC_CHARACTERS_ERROR_MESSAGE')),
            array('authname', 'ext.PhonalisaValidators.uniqueAuthName'),
            array('current_ip, expire_seconds, t38Mode, sip_cid_type, clir_mode', 'length', 'max' => 16),
            array('std_prefix', 'length', 'min' => 1, 'max' => 16, 'allowEmpty' => false, 'on' => 'validateStdPrefix'),
            array('device_name', 'length', 'max' => 64),
            array('typ, state, inc_called_field', 'length', 'max' => 10),
            array(
                'inboundBlacklistId,'
                . 'outboundBlacklistId,'
                . 'scriptExtension,'
                . 'csvImported,'
                . 'providerTemplate,'
                . 'extension_in_contact,'
                . 'inboundWhitelistId,'
                . 'outboundWhitelistId,'
                . 'cid_header_inbound,'
                . 'cid_header_regex_inbound'
                . 'set_sip_headers',
                'safe'
            ), // FIXME
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, name, host, authname, secret, current_ip, device_name, expires, typ, state, inc_called_field, inc_called_search, inc_called_replace', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => __('GATEWAY_MODEL_ID'),
            'name' => __('GATEWAY_MODEL_NAME'),
            'host' => __('GATEWAY_MODEL_HOST'),
            'authname' => __('GATEWAY_MODEL_AUTHNAME'),
            'authusername' => __('GATEWAY_MODEL_AUTHUSERNAME'),
            'secret' => __('GATEWAY_MODEL_SECRET'),
            'current_ip' => __('GATEWAY_MODEL_CURRENT_IP'),
            'device_name' => __('GATEWAY_MODEL_DEVICE_NAME'),
            'expires' => __('GATEWAY_MODEL_EXPIRES'),
            'typ' => __('GATEWAY_MODEL_TYP'),
            'state' => __('GATEWAY_MODEL_STATE'),
            'inc_called_field' => __('GATEWAY_MODEL_INC_CALLED_FIELD'),
            'inc_called_search' => __('GATEWAY_MODEL_INC_CALLED_SEARCH'),
            'inc_called_replace' => __('GATEWAY_MODEL_INC_CALLED_REPLACE'),
            'std_prefix' => __('GATEWAY_MODEL_STD_PREFIX'),
            'dialOutToggle' => __('GATEWAY_MODEL_DIAL_OUT_TOGGLE'),
            'maxChannels' => __('GATEWAY_MODEL_MAX_CHANNELS'),
            'inboundBlacklistId' => __('GATEWAY_MODEL_INBOUND_BLACKLIST_ID'),
            'outboundBlacklistId' => __('GATEWAY_MODEL_OUTBOUND_BLACKLIST_ID'),
            'inboundWhitelistId' => __('GATEWAY_MODEL_INBOUND_WHITELIST_ID'),
            'outboundWhitelistId' => __('GATEWAY_MODEL_OUTBOUND_WHITELIST_ID'),
            'active' => __('GATEWAY_MODEL_ACTIVE'),
            'register' => __('GATEWAY_MODEL_REGISTER'),
            'tcp_transport' => __('GATEWAY_MODEL_TCP_TRANSPORT'),
            'tls_transport' => __('GATEWAY_MODEL_TLS_TRANSPORT'),
            'force_srtp' => __('GATEWAY_MODEL_FORCE_SRTP'),
            'allowed_codecs' => __('GATEWAY_MODEL_ALLOWED_CODECS'),
            'calldeflect_support' => __('GATEWAY_MODEL_CALLDEFLECT_SUPPORT'),
            'caller_id_in_from' => __('GATEWAY_MODEL_CALLER_ID_IN_FROM'),
            'expire_seconds' => __('GATEWAY_MODEL_EXPIRE_SECONDS'),
            'realm' => __('GATEWAY_MODEL_REALM'),
            'from_user' => __('GATEWAY_MODEL_FROM_USER'),
            'from_domain' => __('GATEWAY_MODEL_FROM_DOMAIN'),
            'proxy' => __('GATEWAY_MODEL_PROXY'),
            'register_proxy' => __('GATEWAY_MODEL_REGISTER_PROXY'),
            'contact_params' => __('GATEWAY_MODEL_CONTACT_PARAMS'),
            'ping' => __('GATEWAY_MODEL_PING'),
            'did_in_to' => __('GATEWAY_MODEL_DID_IN_TO'),
            "t38Mode" => __("GATEWAY_MODEL_T_38_MODE"),
            "scriptExtension" => __("USER_MODEL_SCRIPT_EXTENSION"),
            'csvImported' => 'csvImported',
            'providerTemplate' => __('GATEWAY_MODEL_PROVIDER_TEMPLATE'),
            'extension_in_contact' => __('GATEWAY_MODEL_EXTENSION_IN_CONTACT'),
            
            "sip_cid_type" => __("GATEWAY_MODEL_SIP_CID_TYPE"),
            "clir_mode" => __("GATEWAY_MODEL_CLIR_MODE"),
            'clip_no_screening' => __('GATEWAY_MODEL_CLIP_NO_SCREENING'),
            'number_format_cid' => __('GATEWAY_MODEL_NUMBER_FORMAT_CID'),
            'number_format_cid_inbound' => __('GATEWAY_MODEL_NUMBER_FORMAT_CID_INBOUND'),
            'number_format_target' => __('GATEWAY_MODEL_NUMBER_FORMAT_TARGET'),
            'number_format_target_inbound' => __('GATEWAY_MODEL_NUMBER_FORMAT_TARGET_INBOUND'),
            'number_format_target_emergency' => __('GATEWAY_MODEL_NUMBER_FORMAT_TARGET_EMERGENCY'),
            'answer_on_outbound_dial_on_call_forward' => __('GATEWAY_MODEL_ANSWER_ON_OUTBOUND_DIAL_ON_CALL_FORWARD'),
            'unset_sip_headers' => __('GATEWAY_MODEL_UNSET_SIP_HEADERS'),
            'set_sip_headers' => __('GATEWAY_MODEL_SET_SIP_HEADERS'),
            'did_header' => __('GATEWAY_MODEL_DID_HEADER'),
            'did_header_regex' => __('GATEWAY_MODEL_DID_HEADER_REGEX'),
            'cid_header_inbound' => __('GATEWAY_MODEL_CID_HEADER_INBOUND'),
            'cid_header_regex_inbound' => __('GATEWAY_MODEL_CID_HEADER_REGEX_INBOUND'),
            'meta1' => __('GATEWAY_MODEL_META1'),
            'debug' =>  __('GATEWAY_MODEL_DUMP_DEBUG_VARS'),
            "hasAdditionalData" => __("GATEWAY_MODEL_SHOW_ADDITIONAL_DATA"),
            
            "intl_prefix" => __("GATEWAY_MODEL_INTL_PREFIX_WITH_RANGE"),
            "area_code" => __("GATEWAY_MODEL_AREA_CODE"),
            "head_number" => __("GATEWAY_MODEL_HEAD_NUMBER"),
            'did_from' => __("GATEWAY_MODEL_DID_FROM"),
            'did_to' => __("GATEWAY_MODEL_DID_TO"),
            'allow_unauth_calls_from_this_host' => __('GATEWAY_ALLOW_UNAUTH_CALLS_FROM_THIS_HOST')
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CPhonalisaDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    /* 	//create DefaultValue for new Gateways(maybe SQL-addicted)
      public function getLastPrefix() {

      $criteria=new CDbCriteria;
      $criteria->compare('id',$this->id);
      die(print_r($criteria));

      return $criteria;
      }
     */

    public function search($order = 'name')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $filter = $this->getFilter($criteria, $order);

        $filter['pagination'] = array(
            'pageSize' => getGridPageSize('gateway-grid'),
        );

        if ($filter != null) {
            $dataprovider = new CPhonalisaDataProvider($this, $filter);
            $routingGatewayMax = PhonalisaLicenseManager::routingGatewayMax();
            if ($routingGatewayMax >= 0) {
                $dataprovider->pagination->pageSize = $dataprovider->pagination->pageSize > $routingGatewayMax ? $routingGatewayMax : $dataprovider->pagination->pageSize;
                $dataprovider->totalItemCount = $dataprovider->totalItemCount > $routingGatewayMax ? $routingGatewayMax : $dataprovider->totalItemCount;
            }
            return $dataprovider;
        }
    }

    public function renderState(PhonalisaRecord $data, $row)
    {
        if ($data->register == "1") {
            $state = '';
            if ($data->state == "REGED") {
                $state.= '<span class="label label-success" data-translation-id= "GATEWAY_MODEL_GATEWAY_STATE_REGISTERED">' . __("GATEWAY_MODEL_GATEWAY_STATE_REGISTERED") . '</span>';
            } else {
                $state.= '<span class="label" data-translation-id="GATEWAY_MODEL_GATEWAY_STATE_UNREGISTERED">' . __("GATEWAY_MODEL_GATEWAY_STATE_UNREGISTERED") . '</span>';
            }
            return $state;
        }
        return "n/a";
    }

    public function beforeValidate()
    {
        if ($this->dialOutToggle == '1') {
            $this->scenario = "validateStdPrefix";
        } else {
            $this->std_prefix = "";
        }
        return parent::beforeValidate();
    }

    public function beforeDelete()
    {
        $routinginboundModels = RoutingInbound::model()->findAllByAttributes(array('gw_id' => $this->id));
        foreach ($routinginboundModels as $routinginboundModel) {
            $routinginboundModel->delete();
        }
        $routingOutboundModels = RoutingOutbound::model()->findAllByAttributes(array('gw_id' => $this->id));
        foreach ($routingOutboundModels as $routingOutboundModel) {
            $routingOutboundModel->delete();
        }
        return parent::beforeDelete();
    }

    public function afterSave()
    {
        if ($this->isNewRecord) {
            $this->addDefaultRoutesToGateway();
        }
        return parent::afterSave();
    }

    protected function addDefaultRoutesToGateway()
    {
        $gatewayModels = Gateway::model()->countAllByAttributes(array());
        if ($gatewayModels <= 1) {
            $this->addDefaultOutboundRoute();
        }
        if (isset($this->did_to) && isset($this->did_from)) {
            $didRange = (int) $this->did_to - (int) $this->did_from;
            if ($didRange <= 20) {
                $centralInterceptPositionData = array(
                    'sort' => '0',
                    'target' => cfg('DP_DROPTARGET'),
                    'targetType' => TargetType::CentralDropTarget,
                    'pattern' => $this->did_from,
                    'patternType' => PatternType::ExtensionRange
                );
                $this->addDefaultInboundRoute($centralInterceptPositionData);
            }
        }
        $routingInboundSort = RoutingInbound::model()->countAllByAttributes(array('gw_id' => $this->id));
        $sort = (int) $routingInboundSort + 1;
        $DIDData = array(
            'sort' => $sort,
            'target' => RoutingInbound::TARGET_PATTERN_EXTENSION,
            'targetType' => TargetType::Extension,
            'pattern' => RoutingInbound::TARGET_PATTERN_ALL_NUMBERS,
            'patternType' => PatternType::DID
        );
        $this->addDefaultInboundRoute($DIDData);

        $centralDropTargetRule = array(
            'sort' => $sort + 1,
            'target' => cfg('DP_DROPTARGET'),
            'targetType' => TargetType::CentralDropTarget,
            'pattern' => '*',
            'patternType' => PatternType::Manual
        );
        $this->addDefaultInboundRoute($centralDropTargetRule);
    }

    protected function addDefaultOutboundRoute()
    {
        $routingOutbound = new RoutingOutbound();
        $routingOutbound->gw_id = $this->id;
        $routingOutbound->pattern = '*';
        $routingOutbound->targetType = TargetType::Manual;
        $routingOutbound->sort = '0';
        $routingOutbound->active = '1';
        $routingOutbound->save();
    }

    protected function addDefaultInboundRoute($data)
    {
        $routingInbound = new RoutingInbound();
        $routingInbound->gw_id = $this->id;
        $routingInbound->target = $data['target'];
        $routingInbound->targetType = $data['targetType'];
        $routingInbound->pattern = $data['pattern'];
        $routingInbound->patternType = $data['patternType'];
        $routingInbound->sort = $data['sort'];
        $routingInbound->active = '1';
        $routingInbound->save();
    }

    public function renderActiveGateway(PhonalisaRecord $data, $row)
    {
        $active = '';
        if ($data->active == '1') {
            $active.= '<span class="icon-ok" data-gatewayid="' . $data->id . '"></span>';
        } else {
            $active.= '<span class="icon-remove" data-gatewayid="' . $data->id . '"></span>';
        }
        return $active;
    }

    public function t38ModeListData()
    {
        return array(
            T38Mode::NONE => T38Mode::getHumanReadable(T38Mode::NONE),
            T38Mode::SELF => T38Mode::getHumanReadable(T38Mode::SELF),
            T38Mode::PEER => T38Mode::getHumanReadable(T38Mode::PEER),
            T38Mode::PASSTHROUGH => T38Mode::getHumanReadable(T38Mode::PASSTHROUGH)
        );
    }

    public function cidTypeListData()
    {
        return array(
            CIDType::NONE => CIDType::getHumanReadable(CIDType::NONE),
            CIDType::RPID => CIDType::getHumanReadable(CIDType::RPID),
            CIDType::PID => CIDType::getHumanReadable(CIDType::PID)
        );
    }
    
    public function numberFormatListData()
    {
        return array(
            NumberFormat::None => NumberFormat::getHumanReadable(NumberFormat::None),
            NumberFormat::E164WithPlus => NumberFormat::getHumanReadable(NumberFormat::E164WithPlus),
            NumberFormat::E164WithDoubleNull => NumberFormat::getHumanReadable(NumberFormat::E164WithDoubleNull),
            NumberFormat::E164WithoutNullAndPlus => NumberFormat::getHumanReadable(NumberFormat::E164WithoutNullAndPlus),
        );
    }

    public function emergencyNumberFormatListData()
    {
        $listData = $this->numberFormatListData();
        $listData[NumberFormat::LikeOutboundSetting] = NumberFormat::getHumanReadable(NumberFormat::LikeOutboundSetting);
        return $listData;
    }

    public function didHeaderListData() {
        
        return array(
            SIPHeader::NONE => SIPHeader::getHumanReadable(SIPHeader::NONE),
            SIPHeader::TO => SIPHeader::getHumanReadable(SIPHeader::TO),
            SIPHeader::CONTACT => SIPHeader::getHumanReadable(SIPHeader::CONTACT),
            SIPHeader::P_CALLED_PARTY_ID => SIPHeader::getHumanReadable(SIPHeader::P_CALLED_PARTY_ID),
            SIPHeader::REMOTE_PARTY_ID => SIPHeader::getHumanReadable(SIPHeader::REMOTE_PARTY_ID),
        );
    }
    
    public function cidHeaderListData () {
        return array(
            SIPHeader::NONE => SIPHeader::getHumanReadable(SIPHeader::NONE),
            SIPHeader::FROM => SIPHeader::getHumanReadable(SIPHeader::FROM),
            SIPHeader::P_ASSERTED_IDENTITY => SIPHeader::getHumanReadable(SIPHeader::P_ASSERTED_IDENTITY),
            SIPHeader::P_PREFERRED_IDENTITY => SIPHeader::getHumanReadable(SIPHeader::P_PREFERRED_IDENTITY),
            SIPHeader::REMOTE_PARTY_ID => SIPHeader::getHumanReadable(SIPHeader::REMOTE_PARTY_ID),
        );
    }

    public function clirModeListData () {
        return array(
            CLIRMode::NotSupported => CLIRMode::getHumanReadable(CLIRMode::NotSupported),
            CLIRMode::PrivacyHeader => CLIRMode::getHumanReadable(CLIRMode::PrivacyHeader),
            CLIRMode::CIDToAnon => CLIRMode::getHumanReadable(CLIRMode::CIDToAnon),
        );
    }
    
    public function getExportNotRelevantAttributes()
    {
        return array(
            'state',
            'inc_called_field',
            'inc_called_replace',
            'inc_called_search',
            'csvImported',
            'current_ip',
            'device_name',
            'expires'
        );     
    }
    
    protected function getDataFromINI()
    {
        $contents = file_get_contents(dirname(__FILE__) . "/../ini/provider.ini");
        $contents = explode("\n", $contents);
        $config = array();
        $currentsection = "";
        foreach ($contents as $line) {
            $line = trim($line);
            if (strlen($line) == 0) {
                continue;
            }
            if ($line[0] == "[") {
                $currentsection = $line;
                $currentsection = trim($currentsection, "][ ");
                continue;
            }
            if (!startsWith($currentsection, '_') || app()->params->devMode) {
                $parts = explode("=", $line, 2);
                $key = trim($parts[0]);
                $value = trim(@$parts[1]);
                $config[$currentsection][$key] = $value;
            }
        }
        return $config;
    }

    public function getProviderChoose()
    {
        $data = array();
        $templateData = $this->getDataFromINI();
        foreach ($templateData as $key => $value) {
            if ($value["humanname"] === "default") {
                $data[$key] = __('GATEWAY_MODEL_PROVIDER_TEMPLATE_EMPTY');
            } else {
                $data[__("GLOBAL_COUNTRY_NAME_" . $value['country'])][$key] = $value['humanname'];
            }
            
        }
        return $data;
    }
 
    public function getTemplateSettingsFromProviderIni($template)
    {
        $templateData = $this->getDataFromINI();
        if (isset($templateData[$template])) {
            return array_merge($templateData[$template], array("providerTemplate" => $template));
        } else {
            throw new CHttpException(500, "Template template '$template' is not defined!");
        }
    }
    
    public function isRequiredByTemplate($attr)
    {
        $templateData = $this->getTemplateSettingsFromProviderIni($this->providerTemplate);
        $fields = explode(",", $templateData["fields"]);

        $optional = array(
            // checkboxes : 
            "register",
            "active",
            "dialOutToggle",
            "hasAdditionalData",
            "caller_id_in_from",
            "did_in_to",
            "tcp_transport",
            "tls_transport",
            "force_srtp",
            "calldeflect_support",
            "answer_on_outbound_dial",
            "extension_in_contact",
            "clip_no_screening",
            "answer_on_outbound_dial_on_call_forward",
            "debug",
            // location fields:
            "intl_prefix",
            "area_code",
            "head_number"
        );
        
        if (in_array($attr, $fields) && !in_array($attr, $optional)) {
            return true;
        }
        
        return false;
    }
}