// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {TrustCertView}
 */
define(['fs/presenter/settings/trustcertificate/TrustCertPresenter',
        'text!fsPages/settings/trustcertificate/trustcert.html',
        'text!fsPages/settings/trustcertificate/upload_ca_cert.html',
        'hp/view/DialogView',
        'hp/core/EventDispatcher',
        'hp/core/Localizer',
        'hp/view/FormStateView',
        'hp/model/Session',
        'jquery',
        'hp/lib/jquery.hpCollapsible'],
function(presenter, trustCertHtml, uploadCACertHtml, DialogView,
         EventDispatcher, Localizer, FormStateView, session) {"use strict";

    var TrustCertView = (function() {
        var TECH_DETAIL_LIST = '#fs-trust-certificate-techdetail-list',
            CERT_DETAIL_LIST = '#fs-trust-certificate-certdetail-list',
            HEADER = '#fs-trust-certificate-header',
            TRUST_QUEST = '#fs-trust-certificate-trustcertquest-label',
            WEB_SERVER_CERT_FIELDSET = '#fs-trust-certificate-set-certificate-info-1',
            CA_CERT_FIELDSET = '#fs-trust-certificate-set-certificate-info-2',
            COLLAPSE = '#fs-trust-certificate-set-tech-details',
            CERTINFO_HEADER = '#fs-trust-certificate-certinfo-header',
            CA_CERT_FIELDSET_ID = 'fs-trust-certificate-set-certificate-info-2',
            OK = '#fs-trust-certificate-trustok',
            CANCEL = '#fs-trust-certificate-cancel',
            CANCEL_UPLOAD = '#fs-root-certificate-cancel',
            ADD_UPLOAD = '#fs-root-certificate-add',
            LABEL_CLASS = '.fs-trust-cert-label',
            VALUE_CLASS = '.fs-trust-cert-value',
            FORM = '#fs-root-certificate-form',
            CA_CERT_BASE64_DATA = '#fs-root-certificate-base64-text';

        var COMMON_NAME = "commonName",
            ALT_NAME = "alternativeName",
            VALID_FROM = "validFrom",
            VALID_UNTIL = "validUntil",
            ORGANIZATION = "organization",
            LOCALITY = "locality",
            STATE = "state",
            COUNTRY = "country",
            BASE64DATA = "base64Data",
            PUBLIC_KEY = "publicKey";

        var ENABLE = "enable",
            DISABLE = "disable",
            REVOKED = "revoked",
            NOT_AUTHORIZED = "not_authorized",
            INVALID_CHAIN = "invalid_chain";

        var certDetails = {
            version : Localizer.getString("fs.settings.certificate.truststore.version"),
            serialNumber : Localizer.getString("fs.settings.certificate.truststore.serial_number"),
            commonName : Localizer.getString("fs.settings.certificate.truststore.common_name"),
            issuer : Localizer.getString("fs.settings.certificate.truststore.issuer"),
            alternativeName : Localizer.getString("fs.settings.certificate.truststore.alternative_name"),
            linebreak1 : true,
            sha1Fingerprint : Localizer.getString("fs.settings.certificate.truststore.sha1_fingerprint"),
            md5Fingerprint : Localizer.getString("fs.settings.certificate.truststore.md5_fingerprint"),
            signatureAlgorithm : Localizer.getString("fs.settings.certificate.truststore.signature_algorithm"),
            linebreak2 : true,
            validFrom : Localizer.getString("fs.settings.certificate.truststore.valid_from"),
            linebreak3 : true,
            publicKey : Localizer.getString("fs.settings.certificate.truststore.public_key")
        };

        var certSummary = {
            commonName : Localizer.getString("fs.settings.certificate.truststore.issued_to"),
            issuer : Localizer.getString("fs.settings.certificate.truststore.issued_by"),
            validFrom : Localizer.getString("fs.settings.certificate.truststore.valid_from")
        };

        //Events to be listened for by Pulsar
        var GET_CERT_SUCCESS = "getCertificateSuccess",//1. cert is retrieved successfully
                                                       //from remote appliance
            //2. cert could not be retrieved from remote appliance
            GET_CERT_ERROR = "getCertificateError",
            //3. cert retrieved from remote appliance already exists in trust store
            CERT_ALREADY_TRUSTED = "certificateAlreadyTrusted",
            //4. user clicked on 'YES,Trust cert'
            TRUST_CERT_AGREE = "trustCertificateAgree",
            //5. user clicked on 'NO, Dont trust cert'
            TRUST_CERT_DISAGREE = "trustCertificateDisagree",
            //6. Cert of remote appliance is successfully imported into trust store
            TRUST_CERT_SUCCESS = "trustCertificateSuccess",
            //7. cert of remote appliance could not be stored in trust store
            TRUST_CERT_FAIL = "trustCertificateFailure",
            //8. CA cert uploaded by user is successfully imported into trust store AND
            //the uploaded CA cert is valid for the remote appliance
            IMPORT_ROOT_SUCCESS = "importCACertSuccess",
            //9. CA cert uploaded by user is imported but INVALID for the remote appliance
            IMPORT_ROOT_FAIL = "importCACertFailure",
            //10. User clicks on 'Cancel' and does not upload CA cert as asked
            IMPORT_ROOT_CANCEL = 'importCACertCancel',
            //11.User does not have authorization to view certificate details
            GET_CERT_NOAUTH = "getCertificateAuthError";


        function TrustCertView() {
            var dispatcher = new EventDispatcher();
            var formStateView = new FormStateView();
            var hostname='';
            var aliasName = null;
            var certToImport = {};
            var errorCount = 0;
            var errorList = [];
            var validator;
            var uploadRoot = false;
            var isSubmitted = false;
            var importSuccess = false;
            var br = $('<br/>');
            var dialog = undefined;
            var validation_msgs = {summary: '', children: []};
            var smallItemTemplate =
                $('<li class="hp-form-item">'+
                '<label class="fs-trust-cert-label"></label>'+
                '<div class="hp-form-content">'+
                '<label class="fs-trust-cert-value hp-value"></label>'+
                '</div>'+
                '</li>');
            var largeItemTemplate =
                $('<li class="hp-form-item">'+
                '<label class="fs-trust-cert-label"></label>'+
                '<div class="hp-form-content hp-wide">'+
                '<textarea class="fs-trust-cert-value hp-comment-form-text" cols=50 rows=10 readonly=true></textarea>'+
                '</div>'+
                '</li>');

            this.on = function(eventName, callback) {
                dispatcher.on(eventName, callback);
            };

            this.off = function(eventName, callback) {
                dispatcher.off(eventName, callback);
            };

            function reset() {
                validation_msgs = {summary: '',children: []};
                hostname='';
                aliasName = null;
                errorCount = 0;
                errorList = [];
                dialog = undefined;
                certToImport = {};
                isSubmitted = false;
                if (uploadRoot){
                    if(validator){
                        validator.resetForm();
                    }
                    formStateView.reset();
                }
                uploadRoot = false;
                importSuccess = false;
            }

            /**
              * Modify some values before display
              *
              * @param key string The key value
              * @param data string The data object
              * @param isSummary boolean true if summary block, false if details block
              * @returns
              */
            function getKeyValue(key, data, isSummary){
                var returnVal = data[key];
                if (key === PUBLIC_KEY){
                    returnVal = $.trim(data[key]);//$.trim(data[key].substring(data[key].indexOf("modulus")));
                }else if (key === COMMON_NAME && !isSummary){
                    returnVal = data[key] + ((data[ORGANIZATION] === undefined)? "" : ", "+data[ORGANIZATION])+
                                ((data[LOCALITY] === undefined)? "" : ", "+data[LOCALITY]) +
                                ((data[STATE] === undefined)? "" : ", "+data[STATE]) +
                                ((data[COUNTRY] === undefined)? "" : ", "+data[COUNTRY]);
                }else if (key === VALID_FROM){
                    var valid_from = $.format.date(Date.parseISOString(data[VALID_FROM]), 'MMM d, yyyy hh:mm a');
                    var valid_until = $.format.date(Date.parseISOString(data[VALID_UNTIL]), 'MMM d, yyyy hh:mm a')+Date.tzOffsetString();
                    returnVal = valid_from + " "+
                                Localizer.getString("fs.settings.certificate.truststore.to") + " " +
                                valid_until;
                }
                return returnVal;
            }

            /**
             * Construct the certificate summary block
             * @param pageSection The section of the page being modified
             * @param data
             */
            function constructCertSummaryBlock(pageSection, data){
                var keys = Object.keys(certSummary);
                $(CERT_DETAIL_LIST, pageSection).empty();
                $.each(keys, function(index, key) {
                    var item = smallItemTemplate.clone();
                    $(LABEL_CLASS, item).text(certSummary[key]);
                    $(VALUE_CLASS, item).text(getKeyValue(key, data, true));
                    $(CERT_DETAIL_LIST, pageSection).append(item);
                });
            }

            /**
             * Construct the certificate details block
             * @param pageSection The section of the page being modified
             * @param data
             */
            function constructTechDetailsBlock(pageSection, data){
                var keys = Object.keys(certDetails);
                $(TECH_DETAIL_LIST, pageSection).empty();
                $.each(keys, function(index, key) {
                    if (/^linebreak/.test(key)){
                        $(TECH_DETAIL_LIST, pageSection).append(br.clone()).append(br.clone());
                    }else{
                        if (data[key] !== null && data[key] !== undefined){
                            var item = (key === PUBLIC_KEY)? largeItemTemplate.clone() : smallItemTemplate.clone();
                            $(LABEL_CLASS, item).text(certDetails[key]);
                            $(VALUE_CLASS, item).text(getKeyValue(key, data, false));
                            $(TECH_DETAIL_LIST, pageSection).append(item);
                        }
                    }
                });
            }

            function getAndAssignCertificateReadableContent(pageSection, data){
                constructCertSummaryBlock(pageSection, data);
                constructTechDetailsBlock(pageSection, data);
            }

            /**
             * Sets the validation messages in the dialog
             * @param data
             */
            function setValidations(data){
                if (validation_msgs.children.length >= 1){
                    validation_msgs.summary = Localizer.getString("fs.settings.certificate.truststore.connection_untrusted_warn");
                    if (validation_msgs.children.length === 1){
                        var details = validation_msgs.children[0].details;
                        validation_msgs.children = [];
                        validation_msgs.details = details;
                    }
                    dialog.setMessage(validation_msgs);
                }
            }

            /**
             * Check the certificate status
             * @param data
             */
            function getAndAssignCertificateStatus(data){
                if (data.certificateStatus.selfsigned === true){
                    var selfSignedMsg = {
                        status: 'info',
                        details: Localizer.getString("fs.settings.certificate.truststore.self_signed_warn")
                    };
                    validation_msgs.children.push(selfSignedMsg);
                }else{
                    if (data.certificateStatus.issuerTrusted === false){
                        var issuerTrustedMsg = {
                            status: 'info',
                            details: Localizer.getString("fs.settings.certificate.truststore.issue_untrusted_warn")
                        };
                        validation_msgs.children.push(issuerTrustedMsg);
                    }
                }
                if (data.certificateStatus.status === "EXPIRED"){
                    var statusMsg = {
                        status: 'info',
                        details: Localizer.getString("fs.settings.certificate.truststore.invalid_warn")
                    };
                    validation_msgs.children.push(statusMsg);
                }
                if (!checkHostnameExists(data.certificateDetails[0])){
                    var hostNotExistsMsg = {
                        status: 'info',
                        details: Localizer.getString("fs.settings.certificate.truststore.hostname_not_found_warn")
                    };
                    validation_msgs.children.push(hostNotExistsMsg);
                }
                setValidations(data);
            }

            /**
             * Set up the dialog
             */
            function addInfoToDialog(){
                //the dialog header
                $(HEADER).text(Localizer.getString("fs.settings.certificate.truststore.variableheader", [hostname]));
                //initialize collapsible field for web server cert
                $(COLLAPSE, WEB_SERVER_CERT_FIELDSET).hpCollapsible();
            }

            /**
             * Empty the dialog of everything except validation messages
             * @param error
             */
            function prepareDialogForError(error){
                $(WEB_SERVER_CERT_FIELDSET).hide();
                $(CA_CERT_FIELDSET).hide();
                $(TRUST_QUEST).hide();
                $(OK).hide();
                $(CANCEL).addClass("hp-primary").text(Localizer.getString("fs.settings.certificate.truststore.close"));
                if (error === REVOKED){
                    dialog.setMessage({
                        summary : Localizer.getString("fs.settings.certificate.truststore.revoked_msg"),
                        resolution : Localizer.getString("fs.settings.certificate.truststore.revoked_resol")
                    });
                }else if (error === NOT_AUTHORIZED){
                    dialog.setMessage({
                        summary : Localizer.getString("fs.settings.certificate.truststore.not_auth"),
                        resolution : Localizer.getString("fs.settings.certificate.truststore.not_auth_resol")
                    });
                }else if (error === INVALID_CHAIN){
                    dialog.setMessage({
                        summary : Localizer.getString("fs.settings.certificate.truststore.invalid_chain"),
                        resolution : Localizer.getString("fs.settings.certificate.truststore.invalid_chain_resol")
                    });
                }
            }

            function createAndReturnCertificateObject(aliasName, base64Data){
                var certObject = {
                         type : "SSLCertificateDTO",
                         base64SSLCertData : certToImport.base64Data,
                         aliasName : aliasName,
                         verifyTrustChainAndRevocation : true,
                         verifyRevocationStatus : true
                     };
                return certObject;
            }

            /**
             * Call to import certificate
             * @param type
             */
            function postCertificate(type){
                if (type ==="root"){
                    aliasName = null;//will be set to common name in backend
                    certToImport[BASE64DATA] = $(CA_CERT_BASE64_DATA).val();
                }
                var certObject = createAndReturnCertificateObject(aliasName);
                presenter.importCertificate(certObject);
            }

            function enableDisableButtons(action){
                if (action === ENABLE){
                    $(ADD_UPLOAD).removeClass("hp-disabled");
                    $(CANCEL_UPLOAD).removeClass("hp-disabled");
                }
                else if (action === DISABLE){
                    $(ADD_UPLOAD).addClass("hp-disabled");
                    $(CANCEL_UPLOAD).addClass("hp-disabled");
                }
            }

            /**
             * Call to import certificate
             */
            function importCertificate(){
                if (session.canPerformAction("appliance", "Create") ||
                       session.canPerformAction("appliance", "Update")){
                    if (uploadRoot){
                        if ($(FORM).valid() && isSubmitted === false){
                            postCertificate("root");
                            var infoMsg = Localizer.getString("fs.settings.certificate.truststore.verifying");
                            formStateView.setMessage({summary:infoMsg, status:'info',
                                changing : true});
                            enableDisableButtons(DISABLE);

                        }
                        return false;
                    }else{
                        presenter.addOrUpdateCertificate(aliasName, createAndReturnCertificateObject(aliasName));//import is done if delete is successful
                        dispatcher.fire(TRUST_CERT_AGREE, hostname);
                        return true;
                    }
                }else{
                    dialog.clearMessage();
                    prepareDialogForError(NOT_AUTHORIZED);
                    return false;
                }
            }

            /**
             * Because on success also, we trigger cancel button click to close dialog
             */
            function throwEvent(){
                if (!importSuccess){
                    dispatcher.fire(IMPORT_ROOT_CANCEL, hostname);
                }
            }

            /**
             * If root certificate must be uploaded, initialize that dialog
             */
            function setupUploadCACertDialog(){
                if (!dialog){
                    dialog= new DialogView();
                    dialog.init({
                        contents:uploadCACertHtml,
                        ok : importCertificate,
                        cancel : function() {
                            throwEvent();
                            reset();
                            removeEvents();
                        }});
                    dialog.clearMessage();
                    dialog.setMessage({
                        summary : Localizer.getString(
                            "fs.settings.certificate.truststore.upload_ca_reason", [hostname])
                    });
                    $(CA_CERT_BASE64_DATA).empty();
                    formStateView.init({form: $(FORM)});
                    validator = $(FORM).validate({
                        rules : {
                            caCertBase64Text : {
                               required : true
                            }
                        },
                        messages : {
                            caCertBase64Text : {
                                required : Localizer.getString(
                                    "fs.settings.certificate.truststore.required")
                            }
                        }
                    });
                }
            }

            /**
             * Set up dialog to show only web server cert details
             * @param data
             */
            function setupSingleCertDialog(data){
                $(CERTINFO_HEADER, WEB_SERVER_CERT_FIELDSET).text(
                    Localizer.getString("fs.settings.certificate.truststore.certificate_information"));
                $(TRUST_QUEST).text(Localizer.getString("fs.settings.certificate.truststore.trust_confirm"));
                certToImport[BASE64DATA] = data.certificateDetails[0].base64Data;
                aliasName = hostname; //data.certificateDetails[0][COMMON_NAME];
                getAndAssignCertificateReadableContent(WEB_SERVER_CERT_FIELDSET, data.certificateDetails[0]);
            }

            /**
             * Set up dialog to show both web server cert and CA cert details
             * @param data
             */
            function setupMultipleCertDialog(data){
                //construct the ca cert info area
                var caInfoFieldset = $(WEB_SERVER_CERT_FIELDSET).clone();
                caInfoFieldset.attr('id', CA_CERT_FIELDSET_ID);
                caInfoFieldset.insertBefore(WEB_SERVER_CERT_FIELDSET);

                $(COLLAPSE, CA_CERT_FIELDSET).hpCollapsible();
                $(CERTINFO_HEADER, CA_CERT_FIELDSET).text(
                Localizer.getString("fs.settings.certificate.truststore.ca_info"));
                $(TRUST_QUEST).text(Localizer.getString("fs.settings.certificate.truststore.trust_confirm_multiple"));

                certToImport[BASE64DATA] = data.certificateDetails[data.certificateDetails.length -1].base64Data;
                aliasName = null;//set to null if CA cert, will be set in backend
                //populate the fields for both certificates
                getAndAssignCertificateReadableContent(CA_CERT_FIELDSET,data.certificateDetails[data.certificateDetails.length -1]);
                getAndAssignCertificateReadableContent(WEB_SERVER_CERT_FIELDSET,data.certificateDetails[0]);
            }

            /**
             * If the web server cert or the CA cert retrieved already exists in trust store, it is trusted
             * @returns {Boolean}
             */
            function isTrusted(status){
                return (status.trusted || status.issuerTrusted);
            }

            /**
             * If certificate chain is valid, or self signed certificate is retrieved from remote appliance
             * @param data
             */
            function setupShowCertDialog(data){
                if (!dialog){
                    dialog= new DialogView();
                    dialog.init({
                        contents:trustCertHtml,
                        ok : importCertificate,
                        cancel : function() {
                            reset();
                            removeEvents();
                            dispatcher.fire(TRUST_CERT_DISAGREE, hostname);
                        }
                    });
                    dialog.clearMessage();

                    if (data.certificateStatus.status === "REVOKED"){
                        prepareDialogForError(REVOKED);
                    }
                    else if (data.certificateStatus.chainStatus === "INVALID"){
                        prepareDialogForError(INVALID_CHAIN);
                    }
                    else{
                       addInfoToDialog();
                       //set header for web server cert info, question, store cert and populate fields
                       if (data.certificateDetails.length === 1 ){
                           setupSingleCertDialog(data);
                       }
                       else if (data.certificateDetails.length > 1){
                           setupMultipleCertDialog(data);
                       }
                       getAndAssignCertificateStatus(data);
                    }
                }
            }

            function onGetCertificateSuccess(data){
                dispatcher.fire(GET_CERT_SUCCESS, data);

                if (uploadRoot === false ){//first pass in this function
                    if (data.certificateStatus.chainStatus === "INCOMPLETE"){
                        uploadRoot = true;
                    }

                    if (!isTrusted(data.certificateStatus)){
                        if (uploadRoot){
                            setupUploadCACertDialog();
                        }
                        else{
                            setupShowCertDialog(data);
                        }
                    }else{
                        dispatcher.fire(CERT_ALREADY_TRUSTED, data);
                    }
                }
                else{//if uploadRoot is true, its the second pass in this function
                    if (!isTrusted(data.certificateStatus)){
                        dispatcher.fire(IMPORT_ROOT_FAIL, data);
                    }else{
                        dispatcher.fire(IMPORT_ROOT_SUCCESS, data);//not sure which event Pulsar wants
                    }
                    isSubmitted = true;
                    $(CANCEL_UPLOAD).trigger('click');
                }
            }

            function onGetCertificateError(errorInfo){
                dispatcher.fire(GET_CERT_ERROR, errorInfo);
            }

            /**
             * Construct error messages when import fails
             */
            function importCertFail(errorInfo){
                isSubmitted = false;
                var errorMsg = Localizer.getString(
                    "fs.settings.certificate.truststore.ca_cert_upload_error");
                var errorMsgFormatted = Localizer.formatRestError(errorMsg,errorInfo);
                formStateView.setMessage({summary:errorMsg, status:'error',
                    changing : false, details : errorMsgFormatted});
                enableDisableButtons(ENABLE);
            }

            function onImportCertificateSuccess(data){
                if (uploadRoot){
                    importSuccess = true;
                    presenter.getCertificate(hostname);//trigger a GET to see if the imported certificate causes the appliance to be trusted
                }else{
                    dispatcher.fire(TRUST_CERT_SUCCESS, data);
                }
            }

            function onImportCertificateError(errorInfo){
                if (uploadRoot){
                    importCertFail(errorInfo);
                }else{
                    dispatcher.fire(TRUST_CERT_FAIL, errorInfo);
                }
            }

            function onAddOrUpdateCertificateSuccess(data){
                dispatcher.fire(TRUST_CERT_SUCCESS, data);
            }

            function onAddOrUpdateCertificateError(errorInfo){
                dispatcher.fire(TRUST_CERT_FAIL, errorInfo);
            }

            function registerEvents() {
                presenter.on(GET_CERT_SUCCESS, onGetCertificateSuccess);
                presenter.on(GET_CERT_ERROR, onGetCertificateError);
                presenter.on('importCertificateSuccess', onImportCertificateSuccess);
                presenter.on('importCertificateError', onImportCertificateError);
                presenter.on('addOrUpdateCertificateSuccess', onAddOrUpdateCertificateSuccess);
                presenter.on('addOrUpdateCertificateError', onAddOrUpdateCertificateError);
            }

            function removeEvents() {
                presenter.off(GET_CERT_SUCCESS, onGetCertificateSuccess);
                presenter.off(GET_CERT_ERROR, onGetCertificateError);
                presenter.off('importCertificateSuccess', onImportCertificateSuccess);
                presenter.off('importCertificateError', onImportCertificateError);
                presenter.off('addOrUpdateCertificateSuccess', onAddOrUpdateCertificateSuccess);
                presenter.off('addOrUpdateCertificateError', onAddOrUpdateCertificateError);
            }

            /**
             * Converts ipv6address to full format
             *
             * While comparing ipv6 address1 with ipv6 address2, we convert
             * both addresses into the full form
             * i.e. xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx with 8 sections
             * In the shorthand version ,with a double colon(used to denote
             * consecutive sections of zeroes):
             * xxxx:xxxx::xxxx:xxxx
             * we split the string based on ‘:’ separator and look for a blank
             * space and fill in the blank space with appropriate number of
             * zero filled sections i.e. xxxx:xxxx:0000:0000:0000:0000:xxxx:xxxx
             */
            function convertToFullIPV6Format(ipv6Hostname){
                var zeroes = '0000';
                var addressParts = ipv6Hostname.split(':');
                var numOfParts = addressParts.length;
                if (ipv6Hostname.indexOf('::') > -1){
                    //shorthand
                    for (var c = 0; c < numOfParts ;c++){
                        if (addressParts[c] === ''){//undefined??
                            if (c === 0 || c === (numOfParts-1)){//first or last slot
                                addressParts[c] = zeroes;
                            }else{
                                //This for loop attempts to find out how many
                                //sections are missing in the ipv6 address and
                                //fill in that many sections with the zeroes.
                                for (var n=0; n < 8-(numOfParts-1); n++ ) {
                                    if (n > 0){
                                        addressParts[c] += ':';
                                    }
                                    addressParts[c] += zeroes;
                                }
                            }
                        }
                    }
                    ipv6Hostname = addressParts.join(':');
                }

                //full form
                var addrSections = ipv6Hostname.split(':');
                if (addrSections.length === 8){
                    for (var k =0; k < 8 ;k++){
                        if (addrSections[k].length < 4){
                            var len = addrSections[k].length;
                            for (var z=0;z<4-len;z++){
                                addrSections[k] = '0' + addrSections[k];
                            }
                        }
                    }
                    ipv6Hostname = addrSections.join(':');
                }
                return ipv6Hostname;
            }

            function stripPortFromHostnameAndProcess(hostname){
                var hostnameNoPort = '';
                var port = '';
                if (hostname.match(/:/g) !== null && (hostname.match(/:/g)).length > 1 ){
                    //ipv6
                    if (hostname.indexOf('[') > -1 && hostname.indexOf(']') > -1 ){
                        hostnameNoPort = hostname.substring(hostname.indexOf('[') + 1, hostname.indexOf(']'));
                        port = hostname.substring(hostname.indexOf(']') + 2);
                    }else{
                        hostnameNoPort = hostname;
                    }
                    hostnameNoPort = convertToFullIPV6Format(hostnameNoPort);
                    //replace hostname stored in aliasName with full form
                    if (port === ''){
                        aliasName = hostnameNoPort;
                    }else{
                        aliasName = '[' + hostnameNoPort + ']:' + port;
                    }
                }
                else{
                    //ipv4 - remove the port if it exists
                    if(hostname.indexOf(':') > -1){
                        hostnameNoPort = hostname.split(':')[0];
                    }
                }
                return hostnameNoPort;
            }

            /**
             * Checks if the passed hostname is present in common name or alternative name fields
             * @param data
             */
            function checkHostnameExists(data){
                var retrievedHostname = stripPortFromHostnameAndProcess(hostname);
                //compare
                var matches = false;
                var commonNameStr = data[COMMON_NAME];
                if (data[COMMON_NAME].indexOf(':') > -1){
                    commonNameStr = convertToFullIPV6Format(data[COMMON_NAME]);
                }
                if (retrievedHostname !== commonNameStr){
                    if (data[ALT_NAME]){
                        var altNameArray = data[ALT_NAME].split(",");
                        $.each(altNameArray, function(index, altName){
                            if (altName.indexOf(':') > -1){
                                altName = convertToFullIPV6Format(altName);
                            }
                            if (jQuery.trim(altName) === jQuery.trim(retrievedHostname)){
                                matches = true;
                            }
                        });
                    }
                }else{
                    matches = true;
                }
                return matches;
            }

            this.getCertificate = function(host){
                reset();
                removeEvents();//clear off events in case any are still registered.
                hostname = host;
                registerEvents();//re-register events
                if (session.canPerformAction("appliance","Read")){
                    presenter.getCertificate(host);
                }else{
                    dispatcher.fire(GET_CERT_NOAUTH);
                }
            };
        }
        return  new TrustCertView();
    }());
    return TrustCertView;
});

