// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['hpsum/presenter/server/ServerPresenter',
    'hp/core/Notifications',
    'jquery'],
function(presenter, notifications) { "use strict";

    var ServerAddView = (function() {
      
        var ADD = '#tour-server-add',
            ADD_AGAIN = '#tour-server-add-again',
            CANCEL = '#tour-server-add-cancel',
            NAME = '#tour-server-name';
            
        /**
         * Constructor
         */
        function ServerAddView() {
          
            var addInProgress = false,
                addAgain = false;
          
            function reset() {
                $(NAME).val("");
                $(NAME).focus();
                addInProgress = false;
            }
            
            function onItemAddSuccess(item) {
                notifications.add({
                    summary: localizer.getString('hpsum.common.added'),
                    sourceName: item.name,
                    sourceUri: item.uri,
                    status: 'ok'
                });
                reset();
                addInProgress = false;
            }

            /**
             * @private
             */
            function onItemAddError(errorMessage) {
                notifications.add({summary: errorMessage, status: 'error'});
                addInProgress = false;
            }

            /**
             * @private
             */
            function onAddItem() {
                if(! addInProgress) {
                    addInProgress = true;
                    presenter.addItem({name: $(NAME).val(),
                        category: 'server',
                        uri: '/server/item-' + (new Date()).getTime(),
                        status: 'ok'}, {
                        success : onItemAddSuccess,
                        error : onItemAddError
                    });
                    
                    if (! addAgain) {
                        $(CANCEL).trigger('click');
                    }
                }

                return false;
            }
          
            /**
             * @public
             */
            this.resume = function () {
            };
            
            this.pause = function () {
            };
            
            this.init = function() {
                
                $(ADD).on('click', function(ev) {
                    addAgain = false;
                    onAddItem.call(this);
                    ev.preventDefault();
                });
                $(ADD_AGAIN).on('click', function(ev) {
                    addAgain = true;
                    onAddItem.call(this);
                    ev.preventDefault();
                });
                
                this.resume();
            };
        }

        return new ServerAddView();
    }());
    
    return ServerAddView;
});
