// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/services/settings/trustcertificate/TrustCertService',
        'hp/core/EventDispatcher'],
function(trustCertService, EventDispatcher) { "use strict";

    var TrustCertPresenter = (function() {
        /**
         * @constructor Presentation logic for the Trust certificate page.
         */
        function TrustCertPresenter() {
            var dispatcher = new EventDispatcher();

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

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

            this.getCertificate = function(host) {
                trustCertService.getCertificate(host, {
                    success: function(data){
                        dispatcher.fire("getCertificateSuccess", data);
                    },
                    error: function(errorInfo) {
                        dispatcher.fire("getCertificateError", errorInfo);
                    }
                });
            };

            this.importCertificate = function(certObject) {
                trustCertService.importCertificate(certObject, {
                    success: function(data){
                        dispatcher.fire("importCertificateSuccess", data);
                    },
                    error: function(errorInfo) {
                        dispatcher.fire("importCertificateError", errorInfo);
                    }
                });
            };

            this.addOrUpdateCertificate = function(aliasName, certObject) {
                trustCertService.checkCertificateExists(aliasName, {
                    success: function(data){
                        trustCertService.updateCertificate(aliasName, certObject, {
                            success : function(data){
                                dispatcher.fire("addOrUpdateCertificateSuccess", data);
                            },
                            error : function(errorInfo){
                                dispatcher.fire("addOrUpdateCertificateError", errorInfo);
                            }
                        });
                    },
                    error: function(errorInfo) {
                        trustCertService.importCertificate(certObject, {
                            success : function(data){
                                dispatcher.fire("addOrUpdateCertificateSuccess", data);
                            },
                            error : function(errorInfo){
                                dispatcher.fire("addOrUpdateCertificateError", errorInfo);
                            }
                        });
                    }
                });
            };
       }

        return new TrustCertPresenter();

    }());

    return TrustCertPresenter;

});