<commit_before>
/*
 * Copyright (c) 2015 <NAME>, Inc. All rights reserved.
 */

define([
    'underscore',
    'contrail-config-model',
    'config/networking/port/ui/js/views/portFormatters',
    'config/networking/port/ui/js/models/fixedIPModel',
    'config/networking/port/ui/js/models/allowAddressPairModel',
    'config/networking/port/ui/js/models/dhcpOptionModel',
    'config/networking/port/ui/js/models/fatFlowModel',
    'config/networking/port/ui/js/models/portBindingModel'
], function (_, ContrailConfigModel, PortFormatters, FixedIPModel,
             AllowAddressPairModel, DHCPOptionModel, FatFlowModel,
             PortBindingModel) {
    var portFormatters = new PortFormatters();
    var self;
    var PortModel = ContrailConfigModel.extend({
        defaultConfig: {
            'name': '',
            'display_name': null,
            'fq_name': null,
            'parent_type': 'project',
            'id_perms':{'enable':true},
            'virtual_network_refs':[],
            'virtualNetworkName' : '',
            'port_security_enabled': true,
            //'is_sec_grp_disabled':false,
            'security_group_refs':[],
            'securityGroupValue':'',
            'floating_ip_back_refs':[],
            'floatingIpValue':'',
            'virtual_machine_interface_allowed_address_pairs':{
                        'allowed_address_pair':[]
                    },
            'allowedAddressPairCollection':[],
            'staticRoute':[],
            'virtual_machine_interface_device_owner':'',
            'deviceOwnerValue' : '',
            'logical_router_back_refs':[],
            'logicalRouterValue':'',
            'virtual_machine_refs':[],
            'virtualMachineValue':'',
            'service_health_check_refs':'',
            'virtual_machine_interface_mac_addresses':
                    {
                     'mac_address':[]
                    },
            'macAddress':'',
            'instance_ip_back_refs':[],
            'interface_route_table_refs':[],
            'virtual_machine_interface_dhcp_option_list':{'dhcp_option':[]},
            'dhcpOptionCollection':[],
            'virtual_machine_interface_fat_flow_protocols': {
                'fat_flow_protocol':[]
            },
            'virtual_machine_interface_bindings': {
                'key_value_pair':[]
            },
            'fatFlowCollection': [],
            'portBindingCollection': [],
            'virtual_machine_interface_properties':{
                'sub_interface_vlan_tag':'',
                'local_preference' : "",
                'interface_mirror' : {
                    'traffic_direction' : "both",
                    'mirror_to' : {
                        'analyzer_name': null,
                        'analyzer_ip_address': null,
                        'routing_instance': null,
                        'udp_port': null,
                        'analyzer_mac_address': null,
                        'juniper_header': "enabled",
                        'nh_mode': null,
                        'static_nh_header': {
                            'vtep_dst_ip_address': null,
                            'vtep_dst_mac_address': null,
                            'vni': null
                        },
                        'nic_assisted_mirroring': false,
                        'nic_assisted_mirroring_vlan': null
                    }
                }
            },
            'is_mirror' : false,
            'mirrorToRoutingInstance': "",
            'mirrorToNHMode': "dynamic",
            'user_created_nic_assisted': false,
            'user_created_juniper_header' : "enabled",
            'fixedIPCollection': [],
            'display_name': '',
            'virtual_machine_interface_refs': [],
            'disablePort':false,
            'is_sub_interface':false,
            'subInterfaceVMIValue':'',
            'templateGeneratorData': 'rawData',
            'disable_sub_interface' : false,
            'subnetGroupVisible': true,
            'isParent' : false,
            'ecmp_hashing_include_fields': {/*
                'hashing_configured': false,
                'source_ip': true,
                'destination_ip': true,
                'ip_protocol': true,
                'source_port': true,
                'destination_port': true*/
            },
            'virtual_machine_interface_disable_policy': false,
            'qos_config_refs': [],
            'bridge_domain_refs': [],
            'user_created_bridge_domain': '',
            'user_created_bridge_domain_list': []
        },
        onVNSelectionChanged: function(portFormatters, newValue, mode) {
            var subnetDSDetails = portFormatters.fixedIpSubnetDDFormatter(
                    self.getVNData(),
                    newValue);
            if(subnetDSDetails.flatSubnetIPAMIds.length > 0) {
                self.getFlatSubnets(newValue, subnetDSDetails.flatSubnetIPAMIds,
                        function(flatSubnets) {
                    subnetDSDetails.SubnetDS =
                        subnetDSDetails.SubnetDS.concat(flatSubnets);
                    self.manageFixedIPSection(subnetDSDetails.SubnetDS,
                            mode);
                });
            } else {
                self.manageFixedIPSection(subnetDSDetails.SubnetDS,
                        mode);
            }
            this.getBridgeDomains(newValue);
        },

        manageFixedIPSection: function(subnetDS, mode){
            if(subnetDS.length > 0) {
                self.setSubnetDataSource(subnetDS);
                self.subnetGroupVisible(true);
            } else {
                self.subnetGroupVisible(false);
            }
            if(mode === ctwl.CREATE_ACTION) {
                self.model().attributes.fixedIPCollection.reset();
                self.addFixedIP();
            }
        },

        getBridgeDomains: function(vnName) {
            if(!vnName) {
                return;
            }
            var self = this, ajaxConfig = {};
            ajaxConfig.type = 'POST';
            ajaxConfig.data = JSON.stringify({data: [{type: "bridge-domains",
                parent_type: "virtual-network",
                parent_fq_name_str: vnName}]});
            ajaxConfig.url = ctwc.URL_GET_CONFIG_DETAILS;
            contrail.ajaxHandler(ajaxConfig, null,
                function(response) {
                    self.user_created_bridge_domain_list(
                            portFormatters.bridgeDomainDDFormatter(response));
                    self.bridge_domain_refs(self.user_created_bridge_domain());
                },
                function(error){
                });
        },

        setVNData: function(allNetworks) {
            self.allNetworks = allNetworks;
        },
        getVNData: function() {
            return self.allNetworks;
        },

        getFlatSubnets: function (vnName, ipamIds, callback) {
            if(!vnName || !ipamIds ||
                    !ipamIds.length) {
                return;
            }
            var uniqueIPAMIds = _.unique(ipamIds);
            var self = this, ajaxConfig = {};
            ajaxConfig.type = 'POST';
            ajaxConfig.data = JSON.stringify({data: [{type: "network-ipams",
               obj_uuids: uniqueIPAMIds}]});
            ajaxConfig.url = ctwc.URL_GET_CONFIG_DETAILS;
            contrail.ajaxHandler(ajaxConfig, null,
                function(response) {
                    callback(portFormatters.flatSubnetsDDFormatter(response));
                },
                function(error){
                    callback([]);
                });
        },

        setSubnetDataSource: function(subnetDataSource) {
            self.subnetDataSource = subnetDataSource;
        },
        formatModelConfig: function (config) {
            self = this;
            var modelConfig = $.extend({},true,config);
            modelConfig['rawData'] = config;
            //virtual Network
            var virtualNetwork = getValueByJsonPath(
                                 modelConfig,"virtual_network_refs;0;to",[]);
            if(virtualNetwork.length > 0) {
                modelConfig['virtualNetworkName'] = virtualNetwork.join(":");
            }
            modelConfig['display_name'] = ctwu.getDisplayNameOrName(modelConfig);
            //Modal config default Fqname formatting
            if(modelConfig['fq_name'] != null &&
               modelConfig['fq_name'].length >= 3) {
                modelConfig['name'] = modelConfig['fq_name'][2];
            }

            var mac = getValueByJsonPath(modelConfig,
                      "virtual_machine_interface_mac_addresses;mac_address;0","");
            if(mac != "") {
                modelConfig['macAddress'] =
                    modelConfig['virtual_machine_interface_mac_addresses']['mac_address'][0];
            }

            //Modal config default Securiety Group formatting
            var sgLen = modelConfig['security_group_refs'].length;
            var SG = "";
            var SGVal = "";
            modelConfig['securityGroupValue'] = [];
            for(var i=0;i<sgLen;i++) {
                SG = getValueByJsonPath(modelConfig['security_group_refs'][i],
                                         'to', '');
                if(SG != '') {
                    SGVal = SG.join(":");
                    modelConfig['securityGroupValue'].push(SGVal);
                }
            }
/*            if(modelConfig['security_group_refs'].length <= 0 &&
               modelConfig['is_sec_grp'] !== true) {
                modelConfig['is_sec_grp'] = false;
                modelConfig['is_sec_grp_disabled'] = true;
            }*/
            //Modal config default Floating IP formatting
            if(modelConfig['floating_ip_back_refs'].length > 0) {
                var floatingIPLen = modelConfig['floating_ip_back_refs'].length;
                var uuid = "";
                var to = "";
                var floatingIPVal = "";
                modelConfig['floatingIpValue'] = [];
                for(var i = 0; i < floatingIPLen; i++) {
                    uuid = getValueByJsonPath(
                           modelConfig['floating_ip_back_refs'][i], 'uuid', '');
                    to = getValueByJsonPath(
                         modelConfig['floating_ip_back_refs'][i], 'to', '');
                    var toStr = to.join(":");
                    if(uuid != '') {
                        modelConfig['floatingIpValue'].
                            push(uuid + cowc.DROPDOWN_VALUE_SEPARATOR + toStr);
                    }
                }
            }
            //Modal config default Fixed IP formatting
            var fixedIPModels = [];
            var fixedipList = modelConfig["instance_ip_back_refs"];
            if(fixedipList != null && fixedipList.length > 0) {
                var fixedIPLen = fixedipList.length;
                var localDataSource = [];
                for(var i = 0; i < fixedIPLen; i++) {
                    var fixedIPobj = fixedipList[i];
                    var fixedIP_obj = {};
                    fixedIP_obj.subnetDataSource = [];
                    var fixedIP = getValueByJsonPath(fixedIPobj,
                        "fixedip", null, false);
                    if(fixedIP !== null) {
                        var val = JSON.stringify(
                                  {"subnet_uuid":fixedIP.subnet_uuid});
                        fixedIP_obj.subnetDataSource.push({'text':'',
                                            'value':val})
                        fixedIP_obj.fixedIp = fixedIP.ip;
                        fixedIP_obj.subnet_uuid = fixedIP.subnet_uuid;
                        fixedIP_obj.uuid = fixedIPobj.uuid;
                        fixedIP_obj.disableFIP = true;
                        fixedIP_obj.visibleSubnet = false;
                        var fixedIPModel = new FixedIPModel(fixedIP_obj);
                        fixedIPModels.push(fixedIPModel);
                    }
                }
            }
            var fixedIPCollectionModel = new Backbone.Collection(fixedIPModels);
            modelConfig["fixedIPCollection"] = fixedIPCollectionModel;
            modelConfig['instance_ip_back_refs'] = fixedIPCollectionModel;

            //Modal config default Allow Address pair formatting
            var aap = [];
            var aapList =
              modelConfig["virtual_machine_interface_allowed_address_pairs"]["allowed_address_pair"];
            if(aapList != null && aapList.length > 0) {
                var aapLen = aapList.length;
                for(var i = 0; i < aapLen; i++) {
                    var aap_obj = aapList[i];
                    var allowAddressPairModel =
                                         new AllowAddressPairModel(aap_obj);
                    aap.push(allowAddressPairModel);

                }
            }
            var appCollectionModel = new Backbone.Collection(aap);
            modelConfig['allowedAddressPairCollection'] = appCollectionModel;

            //Modal config default DHCP option formatting
            var dhcpModelArray = [],
                dhcpList = getValueByJsonPath(modelConfig,
                    "virtual_machine_interface_dhcp_option_list;dhcp_option", []);
            if(dhcpList.length) {
                var dhcpLen = dhcpList.length;
                for(var i = 0; i < dhcpLen; i++) {
                    var dhcp_obj = dhcpList[i],
                        dhcpVal = getValueByJsonPath(dhcpList[i],
                            "dhcp_option_value", null, false),
                        dhcpValBytes = getValueByJsonPath(dhcpList[i],
                            "dhcp_option_value_bytes", null, false),
                        dhcp = {}, dhcpOptionModel;
                     dhcp.dhcp_option_name = dhcpList[i].dhcp_option_name;
                     dhcp.dhcp_option_value = dhcpVal;
                     dhcp.dhcp_option_value_bytes = dhcpValBytes;
                     dhcpOptionModel = new DHCPOptionModel(dhcp);
                     dhcpModelArray.push(dhcpOptionModel);
                }
            }
            var dhcpCollectionModel = new Backbone.Collection(dhcpModelArray);
            modelConfig["virtual_machine_interface_dhcp_option_list"]["dhcp_option"]
                                                = dhcpCollectionModel;
            modelConfig['dhcpOptionCollection'] = dhcpCollectionModel;

            //Modal config default Static Route formatting
            var staticRoute = [];
            var srLen = modelConfig['interface_route_table_refs'].length;
            var SR = "";
            var SRVal = "";
            modelConfig['staticRoute'] = [];
            for(var i=0;i<srLen;i++) {
                SR = getValueByJsonPath(modelConfig['interface_route_table_refs'][i],
                                         'to', '');
                if(SR != '') {
                    SRVal = SR.join(":");
                    modelConfig['staticRoute'].push(SRVal);
                }
            }
            //Modal config default Health Check formatting
            healthCheck =  getValueByJsonPath(modelConfig, 'service_health_check_refs', []);
            if (healthCheck.length > 0) {
                var healthCheckTo = getValueByJsonPath(healthCheck[0], 'to', '');
                var healthCheckuuid = getValueByJsonPath(healthCheck[0],
                                         'uuid', '');
                if (healthCheckTo != "" && healthCheckuuid != "") {
                    healthCheckVal = healthCheckTo.join(":") +
                        cowc.DROPDOWN_VALUE_SEPARATOR + healthCheckuuid;
                    modelConfig['service_health_check_refs'] = healthCheckVal;
                }
            }

            //Modal config default qos formatting
            var qosToArry = getValueByJsonPath(modelConfig,
                    "qos_config_refs;0;to", []);
            if(qosToArry.length === 3){
                modelConfig["qos_config_refs"] = qosToArry[0] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + qosToArry[1] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + qosToArry[2];
            } else {
                modelConfig["qos_config_refs"] = "";
            }

            //bridge domain
            var bdRef = getValueByJsonPath(modelConfig,
                    "bridge_domain_refs;0;to", []);
            if(bdRef.length === 4){
                modelConfig["bridge_domain_refs"] = bdRef[0] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + bdRef[1] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + bdRef[2] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + bdRef[3];
                modelConfig["user_created_bridge_domain"] =
                    modelConfig["bridge_domain_refs"];
            } else {
                modelConfig["bridge_domain_refs"] = "";
            }

            //Modal config default ECMP formatting
            var ecmpHashIncFields = [];
            if ('ecmp_hashing_include_fields' in modelConfig) {
                var ecmpHashIncFieldsObj =
                    modelConfig['ecmp_hashing_include_fields'];
                var hashingConfigured = getValueByJsonPath(ecmpHashIncFieldsObj,
                     'hashing_configured', false);

                if (hashingConfigured != false) {
                    for (var key in ecmpHashIncFieldsObj) {
                        if (true == ecmpHashIncFieldsObj[key] &&
                            ecmpHashIncFieldsObj[key] != "hashing_configured") {
                            ecmpHashIncFields.push(key);
                        }
                    }
                }
            }
            modelConfig['ecmp_hashing_include_fields'] =
                ecmpHashIncFields.join(',');

            //mirroring
            var mirrorAnalyzerName = getValueByJsonPath(modelConfig,
                          "virtual_machine_interface_properties;" +
                          "interface_mirror;mirror_to;analyzer_name",
                          "");
            if(mirrorAnalyzerName) {
                var nicAssistedMirroring = getValueByJsonPath(modelConfig,
                        "virtual_machine_interface_properties;" +
                        "interface_mirror;mirror_to;nic_assisted_mirroring",
                        false, false), routingInst, nhMode, jnprHeader;
                modelConfig['is_mirror'] = true;
                modelConfig["user_created_nic_assisted"] = nicAssistedMirroring;
                if(nicAssistedMirroring) {
                    //modelConfig["user_created_nic_assisted"] = "enabled";
                } else {
                    //modelConfig["user_created_nic_assisted"] = "disabled";
                    routingInst =  getValueByJsonPath(modelConfig,
                        "virtual_machine_interface_properties;" +
                        "interface_mirror;mirror_to;routing_instance",
                        ""),
                    nhMode = getValueByJsonPath(modelConfig,
                            "virtual_machine_interface_properties;" +
                            "interface_mirror;mirror_to;nh_mode",
                            ctwc.MIRROR_DYNAMIC),
                    jnprHeader = getValueByJsonPath(modelConfig,
                            "virtual_machine_interface_properties;" +
                            "interface_mirror;mirror_to;juniper_header",
                            true);
                    if (routingInst != "") {
                        modelConfig['mirrorToRoutingInstance'] = routingInst;
                    } else {
                        modelConfig['mirrorToRoutingInstance'] = null;
                    }
                    modelConfig["mirrorToNHMode"] = nhMode;
                    modelConfig["user_created_juniper_header"] =
                            jnprHeader === true ? "enabled" : "disabled";
                }
            } else {
                modelConfig['is_mirror'] = false;
            }

            //Modal config default Fat Flow option formatting
            var fatFlows = [];
            var fatFlowList =
              modelConfig["virtual_machine_interface_fat_flow_protocols"]["fat_flow_protocol"];
            if(fatFlowList != null && fatFlowList.length > 0) {
                var fatFlowLen = fatFlowList.length;
                for(var i = 0; i < fatFlowLen; i++) {
                    var fatFlow_obj = fatFlowList[i];
                    var fatFlowModel = new FatFlowModel(fatFlow_obj);
                    this.enableDisablePort(fatFlowModel);
                    fatFlows.push(fatFlowModel);
                }
            }
            var fatFlowCollectionModel = new Backbone.Collection(fatFlows);
            modelConfig["virtual_machine_interface_fat_flow_protocols"]["fat_flow_protocol"]
                                                = fatFlowCollectionModel;
            modelConfig['fatFlowCollection'] = fatFlowCollectionModel;

            //Modal config default Port Binding formatting
            var portBinding = [];
            var devOwner = getValueByJsonPath(modelConfig, 'virtual_machine_interface_device_owner');
            if ("compute" == devOwner.substring(0,7)) {
                devOwner = "compute";
            }
            var portBindingList =
              modelConfig["virtual_machine_interface_bindings"]["key_value_pair"];
            if(portBindingList != null && portBindingList.length > 0) {
                var portBindingLen = portBindingList.length;
                for(var i = 0; i < portBindingLen; i++) {
                    var port_binding_obj = portBindingList[i];
                    if(port_binding_obj.key == "vnic_type" &&
                       port_binding_obj.value == "direct" ) {
                       port_binding_obj.key = "SR-IOV (vnic_type:direct)";
                    }
                    if(devOwner == "compute" &&
                      (port_binding_obj.key == "SR-IOV (vnic_type:direct)" ||
                       port_binding_obj.key == "vnic_type" ||
                       port_binding_obj.key == "vif_type" ||
                       port_binding_obj.key == "vif_details")) {
                        port_binding_obj.disablePortBindKey = true;
                    }
                    var portBindingModel = new PortBindingModel(port_binding_obj);
                    this.enableDisablePortBindingValue(portBindingModel, "edit");
                    portBinding.push(portBindingModel);
                }
            }
            var portBindingCollectionModel = new Backbone.Collection(portBinding);
            modelConfig["virtual_machine_interface_bindings"]["key_value_pair"]
                                                = portBindingCollectionModel;
            modelConfig['portBindingCollection'] = portBindingCollectionModel;


            //Modal config default Device Owner formatting
            var deviceOwnerValue = "none";
            var devOwner = getValueByJsonPath(modelConfig,
                'virtual_machine_interface_device_owner', "");
            if(devOwner == "network:router_interface"){
                // if it is Logical Router Device Owner
                deviceOwnerValue = "router";
                if("logical_router_back_refs" in modelConfig &&
                   modelConfig["logical_router_back_refs"].length > 0 ){
                    var deviceLRValue = [];
                    var logicalRouterTo =
                        getValueByJsonPath(modelConfig,
                                          "logical_router_back_refs;0;to", []);
                        var logicalRouterUUID =
                        getValueByJsonPath(modelConfig,
                                          "logical_router_back_refs;0;uuid", "");
                    if(logicalRouterTo.length > 0 && logicalRouterUUID != "") {
                        deviceLRValue = logicalRouterTo.join(":") +
                                        cowc.DROPDOWN_VALUE_SEPARATOR +
                                        logicalRouterUUID;
                        modelConfig["logicalRouterValue"] = deviceLRValue;
                        modelConfig["deviceRouterShow"] = true;
                    }
                }
            } else  if("compute" == devOwner.substring(0,7)){
                if("virtual_machine_refs" in modelConfig &&
                   modelConfig["virtual_machine_refs"].length >= 0 ){
                   // if it is VM for Device Owner
                    deviceOwnerValue = "compute";
                    var deviceVMIValue = [];
                    var vmRefTo = getValueByJsonPath(modelConfig,
                               "virtual_machine_refs;0;to", []);
                    var vmUUID = getValueByJsonPath(modelConfig,
                               "virtual_machine_refs;0;uuid", "");
                    if(vmRefTo.length > 0 && vmUUID != "") {
                        deviceVMIValue = vmUUID + cowc.DROPDOWN_VALUE_SEPARATOR
                            + vmRefTo.join(":");
                        modelConfig["virtualMachineValue"] = deviceVMIValue;
                        modelConfig["deviceComputeShow"] = true;
                    }
                }
            } else {
                deviceOwnerValue = devOwner.trim() ? devOwner : "none";
            }

            //Modal config default SubInterface formatting
            var vlanTag = getValueByJsonPath(modelConfig,
                           "virtual_machine_interface_properties;sub_interface_vlan_tag","");
            if(vlanTag != ""){
                if(vlanTag == "addSubInterface")
                    modelConfig["virtual_machine_interface_properties"]["sub_interface_vlan_tag"] = "";
                modelConfig["is_sub_interface"] = true;
                var vmiRefUUID = getValueByJsonPath(modelConfig,
                              "virtual_machine_interface_refs;0;uuid","");
                var vmiRefTo = getValueByJsonPath(modelConfig,
                              "virtual_machine_interface_refs;0;to",[]);
                if(vmiRefUUID != "" && vmiRefTo.length > 0) {
                    var subInterfaceVMI = vmiRefUUID +
                        cowc.DROPDOWN_VALUE_SEPARATOR + vmiRefTo.join(":");
                    modelConfig["subInterfaceVMIValue"] = subInterfaceVMI;
                    modelConfig["disable_sub_interface"] = true;
                }
            }
            var portUUID = getValueByJsonPath(modelConfig, "uuid", null);
            if(vlanTag == "" && portUUID != null) {
                modelConfig['isParent'] = true;
            }
            modelConfig['deviceOwnerValue'] = deviceOwnerValue;

            //permissions
            this.formatRBACPermsModelConfig(modelConfig);

            return modelConfig;
        },
        validations: {
            portValidations: {
                'virtualNetworkName': {
                    required: true,
                    msg: 'Enter a valid Network name.'
                },
                'virtual_machine_interface_properties.sub_interface_vlan_tag' :
                    function(value, attr, finalObj) {
                    if(finalObj.is_sub_interface == true) {
                        var vlantag = value;
                        if(vlantag == null){
                            return "VLAN.";
                        }
                        if(!isNumber(String(vlantag).trim())){
                            return "VLAN has to be a number.";
                        }
                        var vlanVal = Number(String(vlantag).trim());
                        if(vlanVal < 1 || vlanVal > 4094 ){
                            return "VLAN has to be between 1 to 4094";
                        }
                    }
                },
                'virtual_machine_interface_properties.local_preference' :
                    function(value, attr, finalObj) {
                    if(value){
                        var numVal = Number(value);
                        if(isNaN(numVal) || !Number.isInteger(numVal)){
                            return "Local Preference has to be a integer";
                        }
                        if(numVal < 0 || numVal > 4294967295){
                            return "Local Preference has to be between 0 - 4294967295";
                        }
                    }
                },
                'is_sub_interface': function(value, attr, finalObj) {
                    if(value == true && finalObj.deviceOwnerValue.toLowerCase() == "compute") {
                        return "Subinterface cannot be assigned along with Compute Device Owner."
                    }
                },
                'subInterfaceVMIValue': function(value, attr, finalObj) {
                    if(finalObj.is_sub_interface == true &&
                        value.trim() == "" ) {
                            return "Sub Interface cannot be empty.";
                    }
                },
                'macAddress': function(value, attr, finalObj) {
                    if(value.trim() != "" && !isValidMACAddress(value)) {
                        return "Enter valid MAC Address";
                    }
                },
                'floatingIpValue': function(value, attr, finalObj) {
                    if(value.length > 0 &&
                       finalObj.deviceOwnerValue .toLowerCase()== "router") {
                        return "Floating Ip cannot be assigned to Router port";
                    }
                },
                'virtualMachineValue': function(value, attr, finalObj) {
                    if(value == "" &&
                       finalObj.deviceOwnerValue.toLowerCase() == "compute") {
                        return "Device Owner UUID cannot be empty.";
                    }
                },
                'logicalRouterValue': function(value, attr, finalObj) {
                    if(value == "" &&
                       finalObj.deviceOwnerValue.toLowerCase() == "router") {
                        return "Device Owner UUID cannot be empty.";
                    }
                },
                'deviceOwnerValue': function(value, attr, finalObj) {
                    if (value.toLowerCase() == "router") {
                        if (finalObj.isParent == true) {
                            return "Router cannot be set to a parent port.";
                        }
                        if (finalObj.is_sub_interface == true) {
                            return "Router cannot be set to a Sub Interface.";
                        }
                    }
                },
                'portBindingCollection': function(value, attr, finalObj) {
                    if(value.length > 0) {
                        var portBindingLength = value.length;
                        var portBindingArr = [];
                        for(var i = 0; i < portBindingLength; i++) {
                            portBindingArr[i] = {};
                            if(value.models[i].attributes.key() ==
                               "SR-IOV (vnic_type:direct)") {
                                portBindingArr[i].key = "vnic_type";
                            } else {
                                portBindingArr[i].key =
                                        value.models[i].attributes.key();
                            }
                            portBindingArr[i].value =
                                value.models[i].attributes.value()
                            /*if(portBindingArr[i].key == "vnic_type" &&
                               portBindingArr[i].value == "direct" &&
                                finalObj.deviceOwnerValue != "compute") {
                                return "Device owner compute has to be set for SRIOV.";
                            }*/
                        }
                        var key1 = "", key2 = "";
                        for(var i = 0; i < portBindingLength-1; i++) {
                            key1 = portBindingArr[i].key;
                            for(var j = i+1; j < portBindingLength; j++) {
                                key2 = portBindingArr[j].key;
                                if(key1 == key2) {
                                    return "Duplicate value not allowed in Port binding";
                                }
                            }
                        }
                    }
                },
                'fixedIPCollection': function(value, attr, finalObj) {
                    if(value.length > 0) {
                        var fixedIPLength = value.length;
                        var key1 = "", key2 = "";
                        for(var i = 0; i < fixedIPLength-1; i++) {
                            key1 = value.models[i].attributes.subnet_uuid();
                            if(key1 != "") {
                                for(var j = i+1; j < fixedIPLength; j++) {
                                    key2 = value.models[j].attributes.subnet_uuid();
                                    if(key2 != "") {
                                        if(key1 == key2) {
                                            return "Duplicate value not allowed in Fixed IP";
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.analyzer_name': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true) {
                        if(!value) {
                            return "Enter a valid analyzer name";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.analyzer_ip_address': function(value, attr, finalObj) {
                    if((finalObj.is_mirror == true) &&
                            (finalObj.user_created_nic_assisted === false) &&
                            (finalObj.mirrorToNHMode !== ctwc.MIRROR_STATIC)) {
                        if(!isValidIP(value)) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                        if(value && value.split("/").length > 1) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.udp_port': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false) {
                        if(value !== "" && value !== null) {
                            var vlanVal = Number(String(value).trim());
                            if (isNaN(vlanVal) ||
                                    (vlanVal < 1 || vlanVal > 65535)) {
                                return "Enter UDP Port between 1 to 65535";
                            }
                        }
                    }
                },
                'mirrorToRoutingInstance': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true &&
                            finalObj.user_created_juniper_header === "disabled" &&
                            finalObj.user_created_nic_assisted === false) {
                        if (!value || value.trim() == "") {
                            return "Select Routing Instance";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.analyzer_mac_address': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false) {
                        if(value !== null && value !== "") {
                            if(!isValidMACAddress(value)) {
                                return "Enter valid Analyzer MAC Address";
                            }
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.static_nh_header.vtep_dst_mac_address': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false &&
                            finalObj.mirrorToNHMode === ctwc.MIRROR_STATIC) {
                        if(value !== null && value !== "") {
                            if(!isValidMACAddress(value)) {
                                return "Enter valid VTEP Destination MAC Address";
                            }
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.static_nh_header.vtep_dst_ip_address': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false &&
                            finalObj.mirrorToNHMode === ctwc.MIRROR_STATIC) {
                       if(!isValidIP(value)) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                        if(value && value.split("/").length > 1) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.static_nh_header.vni': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false &&
                            finalObj.mirrorToNHMode === ctwc.MIRROR_STATIC) {
                        var vlanVal = Number(String(value).trim());
                        if (isNaN(vlanVal) || vlanVal < 1 || vlanVal > 65535) {
                            return "Enter VxLAN ID between 1 - 65535";
                        }
                    }<commit_msg>Corrected the max VxLAN ID.<commit_after>
/*
 * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'contrail-config-model',
    'config/networking/port/ui/js/views/portFormatters',
    'config/networking/port/ui/js/models/fixedIPModel',
    'config/networking/port/ui/js/models/allowAddressPairModel',
    'config/networking/port/ui/js/models/dhcpOptionModel',
    'config/networking/port/ui/js/models/fatFlowModel',
    'config/networking/port/ui/js/models/portBindingModel'
], function (_, ContrailConfigModel, PortFormatters, FixedIPModel,
             AllowAddressPairModel, DHCPOptionModel, FatFlowModel,
             PortBindingModel) {
    var portFormatters = new PortFormatters();
    var self;
    var PortModel = ContrailConfigModel.extend({
        defaultConfig: {
            'name': '',
            'display_name': null,
            'fq_name': null,
            'parent_type': 'project',
            'id_perms':{'enable':true},
            'virtual_network_refs':[],
            'virtualNetworkName' : '',
            'port_security_enabled': true,
            //'is_sec_grp_disabled':false,
            'security_group_refs':[],
            'securityGroupValue':'',
            'floating_ip_back_refs':[],
            'floatingIpValue':'',
            'virtual_machine_interface_allowed_address_pairs':{
                        'allowed_address_pair':[]
                    },
            'allowedAddressPairCollection':[],
            'staticRoute':[],
            'virtual_machine_interface_device_owner':'',
            'deviceOwnerValue' : '',
            'logical_router_back_refs':[],
            'logicalRouterValue':'',
            'virtual_machine_refs':[],
            'virtualMachineValue':'',
            'service_health_check_refs':'',
            'virtual_machine_interface_mac_addresses':
                    {
                     'mac_address':[]
                    },
            'macAddress':'',
            'instance_ip_back_refs':[],
            'interface_route_table_refs':[],
            'virtual_machine_interface_dhcp_option_list':{'dhcp_option':[]},
            'dhcpOptionCollection':[],
            'virtual_machine_interface_fat_flow_protocols': {
                'fat_flow_protocol':[]
            },
            'virtual_machine_interface_bindings': {
                'key_value_pair':[]
            },
            'fatFlowCollection': [],
            'portBindingCollection': [],
            'virtual_machine_interface_properties':{
                'sub_interface_vlan_tag':'',
                'local_preference' : "",
                'interface_mirror' : {
                    'traffic_direction' : "both",
                    'mirror_to' : {
                        'analyzer_name': null,
                        'analyzer_ip_address': null,
                        'routing_instance': null,
                        'udp_port': null,
                        'analyzer_mac_address': null,
                        'juniper_header': "enabled",
                        'nh_mode': null,
                        'static_nh_header': {
                            'vtep_dst_ip_address': null,
                            'vtep_dst_mac_address': null,
                            'vni': null
                        },
                        'nic_assisted_mirroring': false,
                        'nic_assisted_mirroring_vlan': null
                    }
                }
            },
            'is_mirror' : false,
            'mirrorToRoutingInstance': "",
            'mirrorToNHMode': "dynamic",
            'user_created_nic_assisted': false,
            'user_created_juniper_header' : "enabled",
            'fixedIPCollection': [],
            'display_name': '',
            'virtual_machine_interface_refs': [],
            'disablePort':false,
            'is_sub_interface':false,
            'subInterfaceVMIValue':'',
            'templateGeneratorData': 'rawData',
            'disable_sub_interface' : false,
            'subnetGroupVisible': true,
            'isParent' : false,
            'ecmp_hashing_include_fields': {/*
                'hashing_configured': false,
                'source_ip': true,
                'destination_ip': true,
                'ip_protocol': true,
                'source_port': true,
                'destination_port': true*/
            },
            'virtual_machine_interface_disable_policy': false,
            'qos_config_refs': [],
            'bridge_domain_refs': [],
            'user_created_bridge_domain': '',
            'user_created_bridge_domain_list': []
        },
        onVNSelectionChanged: function(portFormatters, newValue, mode) {
            var subnetDSDetails = portFormatters.fixedIpSubnetDDFormatter(
                    self.getVNData(),
                    newValue);
            if(subnetDSDetails.flatSubnetIPAMIds.length > 0) {
                self.getFlatSubnets(newValue, subnetDSDetails.flatSubnetIPAMIds,
                        function(flatSubnets) {
                    subnetDSDetails.SubnetDS =
                        subnetDSDetails.SubnetDS.concat(flatSubnets);
                    self.manageFixedIPSection(subnetDSDetails.SubnetDS,
                            mode);
                });
            } else {
                self.manageFixedIPSection(subnetDSDetails.SubnetDS,
                        mode);
            }
            this.getBridgeDomains(newValue);
        },

        manageFixedIPSection: function(subnetDS, mode){
            if(subnetDS.length > 0) {
                self.setSubnetDataSource(subnetDS);
                self.subnetGroupVisible(true);
            } else {
                self.subnetGroupVisible(false);
            }
            if(mode === ctwl.CREATE_ACTION) {
                self.model().attributes.fixedIPCollection.reset();
                self.addFixedIP();
            }
        },

        getBridgeDomains: function(vnName) {
            if(!vnName) {
                return;
            }
            var self = this, ajaxConfig = {};
            ajaxConfig.type = 'POST';
            ajaxConfig.data = JSON.stringify({data: [{type: "bridge-domains",
                parent_type: "virtual-network",
                parent_fq_name_str: vnName}]});
            ajaxConfig.url = ctwc.URL_GET_CONFIG_DETAILS;
            contrail.ajaxHandler(ajaxConfig, null,
                function(response) {
                    self.user_created_bridge_domain_list(
                            portFormatters.bridgeDomainDDFormatter(response));
                    self.bridge_domain_refs(self.user_created_bridge_domain());
                },
                function(error){
                });
        },

        setVNData: function(allNetworks) {
            self.allNetworks = allNetworks;
        },
        getVNData: function() {
            return self.allNetworks;
        },

        getFlatSubnets: function (vnName, ipamIds, callback) {
            if(!vnName || !ipamIds ||
                    !ipamIds.length) {
                return;
            }
            var uniqueIPAMIds = _.unique(ipamIds);
            var self = this, ajaxConfig = {};
            ajaxConfig.type = 'POST';
            ajaxConfig.data = JSON.stringify({data: [{type: "network-ipams",
               obj_uuids: uniqueIPAMIds}]});
            ajaxConfig.url = ctwc.URL_GET_CONFIG_DETAILS;
            contrail.ajaxHandler(ajaxConfig, null,
                function(response) {
                    callback(portFormatters.flatSubnetsDDFormatter(response));
                },
                function(error){
                    callback([]);
                });
        },

        setSubnetDataSource: function(subnetDataSource) {
            self.subnetDataSource = subnetDataSource;
        },
        formatModelConfig: function (config) {
            self = this;
            var modelConfig = $.extend({},true,config);
            modelConfig['rawData'] = config;
            //virtual Network
            var virtualNetwork = getValueByJsonPath(
                                 modelConfig,"virtual_network_refs;0;to",[]);
            if(virtualNetwork.length > 0) {
                modelConfig['virtualNetworkName'] = virtualNetwork.join(":");
            }
            modelConfig['display_name'] = ctwu.getDisplayNameOrName(modelConfig);
            //Modal config default Fqname formatting
            if(modelConfig['fq_name'] != null &&
               modelConfig['fq_name'].length >= 3) {
                modelConfig['name'] = modelConfig['fq_name'][2];
            }

            var mac = getValueByJsonPath(modelConfig,
                      "virtual_machine_interface_mac_addresses;mac_address;0","");
            if(mac != "") {
                modelConfig['macAddress'] =
                    modelConfig['virtual_machine_interface_mac_addresses']['mac_address'][0];
            }

            //Modal config default Securiety Group formatting
            var sgLen = modelConfig['security_group_refs'].length;
            var SG = "";
            var SGVal = "";
            modelConfig['securityGroupValue'] = [];
            for(var i=0;i<sgLen;i++) {
                SG = getValueByJsonPath(modelConfig['security_group_refs'][i],
                                         'to', '');
                if(SG != '') {
                    SGVal = SG.join(":");
                    modelConfig['securityGroupValue'].push(SGVal);
                }
            }
/*            if(modelConfig['security_group_refs'].length <= 0 &&
               modelConfig['is_sec_grp'] !== true) {
                modelConfig['is_sec_grp'] = false;
                modelConfig['is_sec_grp_disabled'] = true;
            }*/
            //Modal config default Floating IP formatting
            if(modelConfig['floating_ip_back_refs'].length > 0) {
                var floatingIPLen = modelConfig['floating_ip_back_refs'].length;
                var uuid = "";
                var to = "";
                var floatingIPVal = "";
                modelConfig['floatingIpValue'] = [];
                for(var i = 0; i < floatingIPLen; i++) {
                    uuid = getValueByJsonPath(
                           modelConfig['floating_ip_back_refs'][i], 'uuid', '');
                    to = getValueByJsonPath(
                         modelConfig['floating_ip_back_refs'][i], 'to', '');
                    var toStr = to.join(":");
                    if(uuid != '') {
                        modelConfig['floatingIpValue'].
                            push(uuid + cowc.DROPDOWN_VALUE_SEPARATOR + toStr);
                    }
                }
            }
            //Modal config default Fixed IP formatting
            var fixedIPModels = [];
            var fixedipList = modelConfig["instance_ip_back_refs"];
            if(fixedipList != null && fixedipList.length > 0) {
                var fixedIPLen = fixedipList.length;
                var localDataSource = [];
                for(var i = 0; i < fixedIPLen; i++) {
                    var fixedIPobj = fixedipList[i];
                    var fixedIP_obj = {};
                    fixedIP_obj.subnetDataSource = [];
                    var fixedIP = getValueByJsonPath(fixedIPobj,
                        "fixedip", null, false);
                    if(fixedIP !== null) {
                        var val = JSON.stringify(
                                  {"subnet_uuid":fixedIP.subnet_uuid});
                        fixedIP_obj.subnetDataSource.push({'text':'',
                                            'value':val})
                        fixedIP_obj.fixedIp = fixedIP.ip;
                        fixedIP_obj.subnet_uuid = fixedIP.subnet_uuid;
                        fixedIP_obj.uuid = fixedIPobj.uuid;
                        fixedIP_obj.disableFIP = true;
                        fixedIP_obj.visibleSubnet = false;
                        var fixedIPModel = new FixedIPModel(fixedIP_obj);
                        fixedIPModels.push(fixedIPModel);
                    }
                }
            }
            var fixedIPCollectionModel = new Backbone.Collection(fixedIPModels);
            modelConfig["fixedIPCollection"] = fixedIPCollectionModel;
            modelConfig['instance_ip_back_refs'] = fixedIPCollectionModel;

            //Modal config default Allow Address pair formatting
            var aap = [];
            var aapList =
              modelConfig["virtual_machine_interface_allowed_address_pairs"]["allowed_address_pair"];
            if(aapList != null && aapList.length > 0) {
                var aapLen = aapList.length;
                for(var i = 0; i < aapLen; i++) {
                    var aap_obj = aapList[i];
                    var allowAddressPairModel =
                                         new AllowAddressPairModel(aap_obj);
                    aap.push(allowAddressPairModel);

                }
            }
            var appCollectionModel = new Backbone.Collection(aap);
            modelConfig['allowedAddressPairCollection'] = appCollectionModel;

            //Modal config default DHCP option formatting
            var dhcpModelArray = [],
                dhcpList = getValueByJsonPath(modelConfig,
                    "virtual_machine_interface_dhcp_option_list;dhcp_option", []);
            if(dhcpList.length) {
                var dhcpLen = dhcpList.length;
                for(var i = 0; i < dhcpLen; i++) {
                    var dhcp_obj = dhcpList[i],
                        dhcpVal = getValueByJsonPath(dhcpList[i],
                            "dhcp_option_value", null, false),
                        dhcpValBytes = getValueByJsonPath(dhcpList[i],
                            "dhcp_option_value_bytes", null, false),
                        dhcp = {}, dhcpOptionModel;
                     dhcp.dhcp_option_name = dhcpList[i].dhcp_option_name;
                     dhcp.dhcp_option_value = dhcpVal;
                     dhcp.dhcp_option_value_bytes = dhcpValBytes;
                     dhcpOptionModel = new DHCPOptionModel(dhcp);
                     dhcpModelArray.push(dhcpOptionModel);
                }
            }
            var dhcpCollectionModel = new Backbone.Collection(dhcpModelArray);
            modelConfig["virtual_machine_interface_dhcp_option_list"]["dhcp_option"]
                                                = dhcpCollectionModel;
            modelConfig['dhcpOptionCollection'] = dhcpCollectionModel;

            //Modal config default Static Route formatting
            var staticRoute = [];
            var srLen = modelConfig['interface_route_table_refs'].length;
            var SR = "";
            var SRVal = "";
            modelConfig['staticRoute'] = [];
            for(var i=0;i<srLen;i++) {
                SR = getValueByJsonPath(modelConfig['interface_route_table_refs'][i],
                                         'to', '');
                if(SR != '') {
                    SRVal = SR.join(":");
                    modelConfig['staticRoute'].push(SRVal);
                }
            }
            //Modal config default Health Check formatting
            healthCheck =  getValueByJsonPath(modelConfig, 'service_health_check_refs', []);
            if (healthCheck.length > 0) {
                var healthCheckTo = getValueByJsonPath(healthCheck[0], 'to', '');
                var healthCheckuuid = getValueByJsonPath(healthCheck[0],
                                         'uuid', '');
                if (healthCheckTo != "" && healthCheckuuid != "") {
                    healthCheckVal = healthCheckTo.join(":") +
                        cowc.DROPDOWN_VALUE_SEPARATOR + healthCheckuuid;
                    modelConfig['service_health_check_refs'] = healthCheckVal;
                }
            }

            //Modal config default qos formatting
            var qosToArry = getValueByJsonPath(modelConfig,
                    "qos_config_refs;0;to", []);
            if(qosToArry.length === 3){
                modelConfig["qos_config_refs"] = qosToArry[0] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + qosToArry[1] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + qosToArry[2];
            } else {
                modelConfig["qos_config_refs"] = "";
            }

            //bridge domain
            var bdRef = getValueByJsonPath(modelConfig,
                    "bridge_domain_refs;0;to", []);
            if(bdRef.length === 4){
                modelConfig["bridge_domain_refs"] = bdRef[0] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + bdRef[1] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + bdRef[2] +
                    cowc.DROPDOWN_VALUE_SEPARATOR + bdRef[3];
                modelConfig["user_created_bridge_domain"] =
                    modelConfig["bridge_domain_refs"];
            } else {
                modelConfig["bridge_domain_refs"] = "";
            }

            //Modal config default ECMP formatting
            var ecmpHashIncFields = [];
            if ('ecmp_hashing_include_fields' in modelConfig) {
                var ecmpHashIncFieldsObj =
                    modelConfig['ecmp_hashing_include_fields'];
                var hashingConfigured = getValueByJsonPath(ecmpHashIncFieldsObj,
                     'hashing_configured', false);

                if (hashingConfigured != false) {
                    for (var key in ecmpHashIncFieldsObj) {
                        if (true == ecmpHashIncFieldsObj[key] &&
                            ecmpHashIncFieldsObj[key] != "hashing_configured") {
                            ecmpHashIncFields.push(key);
                        }
                    }
                }
            }
            modelConfig['ecmp_hashing_include_fields'] =
                ecmpHashIncFields.join(',');

            //mirroring
            var mirrorAnalyzerName = getValueByJsonPath(modelConfig,
                          "virtual_machine_interface_properties;" +
                          "interface_mirror;mirror_to;analyzer_name",
                          "");
            if(mirrorAnalyzerName) {
                var nicAssistedMirroring = getValueByJsonPath(modelConfig,
                        "virtual_machine_interface_properties;" +
                        "interface_mirror;mirror_to;nic_assisted_mirroring",
                        false, false), routingInst, nhMode, jnprHeader;
                modelConfig['is_mirror'] = true;
                modelConfig["user_created_nic_assisted"] = nicAssistedMirroring;
                if(nicAssistedMirroring) {
                    //modelConfig["user_created_nic_assisted"] = "enabled";
                } else {
                    //modelConfig["user_created_nic_assisted"] = "disabled";
                    routingInst =  getValueByJsonPath(modelConfig,
                        "virtual_machine_interface_properties;" +
                        "interface_mirror;mirror_to;routing_instance",
                        ""),
                    nhMode = getValueByJsonPath(modelConfig,
                            "virtual_machine_interface_properties;" +
                            "interface_mirror;mirror_to;nh_mode",
                            ctwc.MIRROR_DYNAMIC),
                    jnprHeader = getValueByJsonPath(modelConfig,
                            "virtual_machine_interface_properties;" +
                            "interface_mirror;mirror_to;juniper_header",
                            true);
                    if (routingInst != "") {
                        modelConfig['mirrorToRoutingInstance'] = routingInst;
                    } else {
                        modelConfig['mirrorToRoutingInstance'] = null;
                    }
                    modelConfig["mirrorToNHMode"] = nhMode;
                    modelConfig["user_created_juniper_header"] =
                            jnprHeader === true ? "enabled" : "disabled";
                }
            } else {
                modelConfig['is_mirror'] = false;
            }

            //Modal config default Fat Flow option formatting
            var fatFlows = [];
            var fatFlowList =
              modelConfig["virtual_machine_interface_fat_flow_protocols"]["fat_flow_protocol"];
            if(fatFlowList != null && fatFlowList.length > 0) {
                var fatFlowLen = fatFlowList.length;
                for(var i = 0; i < fatFlowLen; i++) {
                    var fatFlow_obj = fatFlowList[i];
                    var fatFlowModel = new FatFlowModel(fatFlow_obj);
                    this.enableDisablePort(fatFlowModel);
                    fatFlows.push(fatFlowModel);
                }
            }
            var fatFlowCollectionModel = new Backbone.Collection(fatFlows);
            modelConfig["virtual_machine_interface_fat_flow_protocols"]["fat_flow_protocol"]
                                                = fatFlowCollectionModel;
            modelConfig['fatFlowCollection'] = fatFlowCollectionModel;

            //Modal config default Port Binding formatting
            var portBinding = [];
            var devOwner = getValueByJsonPath(modelConfig, 'virtual_machine_interface_device_owner');
            if ("compute" == devOwner.substring(0,7)) {
                devOwner = "compute";
            }
            var portBindingList =
              modelConfig["virtual_machine_interface_bindings"]["key_value_pair"];
            if(portBindingList != null && portBindingList.length > 0) {
                var portBindingLen = portBindingList.length;
                for(var i = 0; i < portBindingLen; i++) {
                    var port_binding_obj = portBindingList[i];
                    if(port_binding_obj.key == "vnic_type" &&
                       port_binding_obj.value == "direct" ) {
                       port_binding_obj.key = "SR-IOV (vnic_type:direct)";
                    }
                    if(devOwner == "compute" &&
                      (port_binding_obj.key == "SR-IOV (vnic_type:direct)" ||
                       port_binding_obj.key == "vnic_type" ||
                       port_binding_obj.key == "vif_type" ||
                       port_binding_obj.key == "vif_details")) {
                        port_binding_obj.disablePortBindKey = true;
                    }
                    var portBindingModel = new PortBindingModel(port_binding_obj);
                    this.enableDisablePortBindingValue(portBindingModel, "edit");
                    portBinding.push(portBindingModel);
                }
            }
            var portBindingCollectionModel = new Backbone.Collection(portBinding);
            modelConfig["virtual_machine_interface_bindings"]["key_value_pair"]
                                                = portBindingCollectionModel;
            modelConfig['portBindingCollection'] = portBindingCollectionModel;


            //Modal config default Device Owner formatting
            var deviceOwnerValue = "none";
            var devOwner = getValueByJsonPath(modelConfig,
                'virtual_machine_interface_device_owner', "");
            if(devOwner == "network:router_interface"){
                // if it is Logical Router Device Owner
                deviceOwnerValue = "router";
                if("logical_router_back_refs" in modelConfig &&
                   modelConfig["logical_router_back_refs"].length > 0 ){
                    var deviceLRValue = [];
                    var logicalRouterTo =
                        getValueByJsonPath(modelConfig,
                                          "logical_router_back_refs;0;to", []);
                        var logicalRouterUUID =
                        getValueByJsonPath(modelConfig,
                                          "logical_router_back_refs;0;uuid", "");
                    if(logicalRouterTo.length > 0 && logicalRouterUUID != "") {
                        deviceLRValue = logicalRouterTo.join(":") +
                                        cowc.DROPDOWN_VALUE_SEPARATOR +
                                        logicalRouterUUID;
                        modelConfig["logicalRouterValue"] = deviceLRValue;
                        modelConfig["deviceRouterShow"] = true;
                    }
                }
            } else  if("compute" == devOwner.substring(0,7)){
                if("virtual_machine_refs" in modelConfig &&
                   modelConfig["virtual_machine_refs"].length >= 0 ){
                   // if it is VM for Device Owner
                    deviceOwnerValue = "compute";
                    var deviceVMIValue = [];
                    var vmRefTo = getValueByJsonPath(modelConfig,
                               "virtual_machine_refs;0;to", []);
                    var vmUUID = getValueByJsonPath(modelConfig,
                               "virtual_machine_refs;0;uuid", "");
                    if(vmRefTo.length > 0 && vmUUID != "") {
                        deviceVMIValue = vmUUID + cowc.DROPDOWN_VALUE_SEPARATOR
                            + vmRefTo.join(":");
                        modelConfig["virtualMachineValue"] = deviceVMIValue;
                        modelConfig["deviceComputeShow"] = true;
                    }
                }
            } else {
                deviceOwnerValue = devOwner.trim() ? devOwner : "none";
            }

            //Modal config default SubInterface formatting
            var vlanTag = getValueByJsonPath(modelConfig,
                           "virtual_machine_interface_properties;sub_interface_vlan_tag","");
            if(vlanTag != ""){
                if(vlanTag == "addSubInterface")
                    modelConfig["virtual_machine_interface_properties"]["sub_interface_vlan_tag"] = "";
                modelConfig["is_sub_interface"] = true;
                var vmiRefUUID = getValueByJsonPath(modelConfig,
                              "virtual_machine_interface_refs;0;uuid","");
                var vmiRefTo = getValueByJsonPath(modelConfig,
                              "virtual_machine_interface_refs;0;to",[]);
                if(vmiRefUUID != "" && vmiRefTo.length > 0) {
                    var subInterfaceVMI = vmiRefUUID +
                        cowc.DROPDOWN_VALUE_SEPARATOR + vmiRefTo.join(":");
                    modelConfig["subInterfaceVMIValue"] = subInterfaceVMI;
                    modelConfig["disable_sub_interface"] = true;
                }
            }
            var portUUID = getValueByJsonPath(modelConfig, "uuid", null);
            if(vlanTag == "" && portUUID != null) {
                modelConfig['isParent'] = true;
            }
            modelConfig['deviceOwnerValue'] = deviceOwnerValue;

            //permissions
            this.formatRBACPermsModelConfig(modelConfig);

            return modelConfig;
        },
        validations: {
            portValidations: {
                'virtualNetworkName': {
                    required: true,
                    msg: 'Enter a valid Network name.'
                },
                'virtual_machine_interface_properties.sub_interface_vlan_tag' :
                    function(value, attr, finalObj) {
                    if(finalObj.is_sub_interface == true) {
                        var vlantag = value;
                        if(vlantag == null){
                            return "VLAN.";
                        }
                        if(!isNumber(String(vlantag).trim())){
                            return "VLAN has to be a number.";
                        }
                        var vlanVal = Number(String(vlantag).trim());
                        if(vlanVal < 1 || vlanVal > 4094 ){
                            return "VLAN has to be between 1 to 4094";
                        }
                    }
                },
                'virtual_machine_interface_properties.local_preference' :
                    function(value, attr, finalObj) {
                    if(value){
                        var numVal = Number(value);
                        if(isNaN(numVal) || !Number.isInteger(numVal)){
                            return "Local Preference has to be a integer";
                        }
                        if(numVal < 0 || numVal > 4294967295){
                            return "Local Preference has to be between 0 - 4294967295";
                        }
                    }
                },
                'is_sub_interface': function(value, attr, finalObj) {
                    if(value == true && finalObj.deviceOwnerValue.toLowerCase() == "compute") {
                        return "Subinterface cannot be assigned along with Compute Device Owner."
                    }
                },
                'subInterfaceVMIValue': function(value, attr, finalObj) {
                    if(finalObj.is_sub_interface == true &&
                        value.trim() == "" ) {
                            return "Sub Interface cannot be empty.";
                    }
                },
                'macAddress': function(value, attr, finalObj) {
                    if(value.trim() != "" && !isValidMACAddress(value)) {
                        return "Enter valid MAC Address";
                    }
                },
                'floatingIpValue': function(value, attr, finalObj) {
                    if(value.length > 0 &&
                       finalObj.deviceOwnerValue .toLowerCase()== "router") {
                        return "Floating Ip cannot be assigned to Router port";
                    }
                },
                'virtualMachineValue': function(value, attr, finalObj) {
                    if(value == "" &&
                       finalObj.deviceOwnerValue.toLowerCase() == "compute") {
                        return "Device Owner UUID cannot be empty.";
                    }
                },
                'logicalRouterValue': function(value, attr, finalObj) {
                    if(value == "" &&
                       finalObj.deviceOwnerValue.toLowerCase() == "router") {
                        return "Device Owner UUID cannot be empty.";
                    }
                },
                'deviceOwnerValue': function(value, attr, finalObj) {
                    if (value.toLowerCase() == "router") {
                        if (finalObj.isParent == true) {
                            return "Router cannot be set to a parent port.";
                        }
                        if (finalObj.is_sub_interface == true) {
                            return "Router cannot be set to a Sub Interface.";
                        }
                    }
                },
                'portBindingCollection': function(value, attr, finalObj) {
                    if(value.length > 0) {
                        var portBindingLength = value.length;
                        var portBindingArr = [];
                        for(var i = 0; i < portBindingLength; i++) {
                            portBindingArr[i] = {};
                            if(value.models[i].attributes.key() ==
                               "SR-IOV (vnic_type:direct)") {
                                portBindingArr[i].key = "vnic_type";
                            } else {
                                portBindingArr[i].key =
                                        value.models[i].attributes.key();
                            }
                            portBindingArr[i].value =
                                value.models[i].attributes.value()
                            /*if(portBindingArr[i].key == "vnic_type" &&
                               portBindingArr[i].value == "direct" &&
                                finalObj.deviceOwnerValue != "compute") {
                                return "Device owner compute has to be set for SRIOV.";
                            }*/
                        }
                        var key1 = "", key2 = "";
                        for(var i = 0; i < portBindingLength-1; i++) {
                            key1 = portBindingArr[i].key;
                            for(var j = i+1; j < portBindingLength; j++) {
                                key2 = portBindingArr[j].key;
                                if(key1 == key2) {
                                    return "Duplicate value not allowed in Port binding";
                                }
                            }
                        }
                    }
                },
                'fixedIPCollection': function(value, attr, finalObj) {
                    if(value.length > 0) {
                        var fixedIPLength = value.length;
                        var key1 = "", key2 = "";
                        for(var i = 0; i < fixedIPLength-1; i++) {
                            key1 = value.models[i].attributes.subnet_uuid();
                            if(key1 != "") {
                                for(var j = i+1; j < fixedIPLength; j++) {
                                    key2 = value.models[j].attributes.subnet_uuid();
                                    if(key2 != "") {
                                        if(key1 == key2) {
                                            return "Duplicate value not allowed in Fixed IP";
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.analyzer_name': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true) {
                        if(!value) {
                            return "Enter a valid analyzer name";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.analyzer_ip_address': function(value, attr, finalObj) {
                    if((finalObj.is_mirror == true) &&
                            (finalObj.user_created_nic_assisted === false) &&
                            (finalObj.mirrorToNHMode !== ctwc.MIRROR_STATIC)) {
                        if(!isValidIP(value)) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                        if(value && value.split("/").length > 1) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.udp_port': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false) {
                        if(value !== "" && value !== null) {
                            var vlanVal = Number(String(value).trim());
                            if (isNaN(vlanVal) ||
                                    (vlanVal < 1 || vlanVal > 65535)) {
                                return "Enter UDP Port between 1 to 65535";
                            }
                        }
                    }
                },
                'mirrorToRoutingInstance': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true &&
                            finalObj.user_created_juniper_header === "disabled" &&
                            finalObj.user_created_nic_assisted === false) {
                        if (!value || value.trim() == "") {
                            return "Select Routing Instance";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.analyzer_mac_address': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false) {
                        if(value !== null && value !== "") {
                            if(!isValidMACAddress(value)) {
                                return "Enter valid Analyzer MAC Address";
                            }
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.static_nh_header.vtep_dst_mac_address': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false &&
                            finalObj.mirrorToNHMode === ctwc.MIRROR_STATIC) {
                        if(value !== null && value !== "") {
                            if(!isValidMACAddress(value)) {
                                return "Enter valid VTEP Destination MAC Address";
                            }
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.static_nh_header.vtep_dst_ip_address': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false &&
                            finalObj.mirrorToNHMode === ctwc.MIRROR_STATIC) {
                       if(!isValidIP(value)) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                        if(value && value.split("/").length > 1) {
                            return "Enter a valid IP In the format xxx.xxx.xxx.xxx";
                        }
                    }
                },
                'virtual_machine_interface_properties.interface_mirror.mirror_to.static_nh_header.vni': function(value, attr, finalObj) {
                    if(finalObj.is_mirror == true && finalObj.user_created_nic_assisted === false &&
                            finalObj.mirrorToNHMode === ctwc.MIRROR_STATIC) {
                        var vlanVal = Number(String(value).trim());
                        if (isNaN(vlanVal) || vlanVal < 1 || vlanVal > 16777215) {
                            return "Enter VxLAN ID between 1 - 16777215";
                        }
                    }
{'fraction_non_alphanumeric': 0.09664515790578114, 'fraction_numerical': 0.0036722274682614627, 'mean_word_length': 1.2943760719766497, 'pattern_counts': {'":': 18, '<': 40, '<?xml version=': 0, '>': 52, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 70, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2139157', 'n_tokens_mistral': 19459, 'n_tokens_neox': 18196, 'n_words': 2961}