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

define(['fs/presenter/activity/ActivityAlertPresenter',
    'hp/core/Localizer',
    'hp/view/DialogView',
    'hp/view/FormStateView',
    'hp/core/Validator',
    'text!fsPages/activity/assign.html',
    'hp/core/HelpMenu',
    'jquery',
    'hp/lib/jquery.hpSearchCombo'],
function (presenter, localizer, DialogView, FormStateView, validator, assignHtml, helpMenu) {
    "use strict";

    var AlertAssignView = (function () {

        var SPINNER = '.hp-spinner';
        var USERNAME = '#hp-assign-username';
        var FORM_ITEMS = '#hp-alert-assign-form-items';
        var FORM = '#hp-alert-assign-form';
        var USERNAME_INPUT = '#hp-assign-username-input';
        var OK = '#hp-alert-assign-ok';
        var CANCEL = '#hp-alert-assign-cancel';
        var PRIMARY = 'hp-primary';
        var ERROR = 'hp-error';
        var MESSAGE_CONTAINER = '.hp-message-container';
        var SEARCH_COMBO = '.hp-search-combo';

        /**
         * Constructor
         */
        function AlertAssignView() {

            var formStateView = new FormStateView();
            var inProgress = false;
            var dialog = null;
            var validator;

            function getPotentialOwners(query, handlers, count, start) {
                presenter.getPotentialOwners(query, {
                    success: function (names) {
                        handlers.success({count: names.length, members: names,
                            start: 0, total: names.length});
                    }
                });
            }

            function onSelectChange(event, value) {
                var searchCombo = $(event.currentTarget).parents(SEARCH_COMBO);
                var messageContainer = searchCombo.siblings(MESSAGE_CONTAINER);
                var errorLabel = messageContainer.children('label.hp-error');
                if (value.length > 0) {
                    searchCombo.removeClass(ERROR);
                    errorLabel.css('display', 'none');
                }
                else {
                    searchCombo.addClass(ERROR);
                    errorLabel.css('display', 'inline-block');
                }
            }

            function showDialog(uris) {
                var contents = $(assignHtml).filter('.hp-dialog');
                var ownerChecked = false;
                var productBook = helpMenu.getProductBook();
                localizer.localizeDom(contents);

                $(USERNAME, contents).
                    hpSearchCombo({getResults: getPotentialOwners,
                        fixedResults: [localizer.getString('fs.activity.unassigned')]});

                $(FORM_ITEMS, contents).hide();
                // This is to setup online help link for assign dialog since it is not routed dialog
                $('.hp-help-current', contents).attr('href','/doc#/' + (productBook ? productBook : '') + '/activity/assign');

                $(SPINNER, contents).hide();

                var resultsForState = presenter.getResultsForState(null, null, uris);

                // if uris is null, getResultsForState will get the selected uris from the resource
                var usableUris = resultsForState.usable.map( function(item) {
                    return item.uri;
                });

                if (resultsForState.usable.length > 0) {

                    setTimeout(function () {
                        if (! ownerChecked) {
                            $(SPINNER, contents).show();
                        }
                    }, 200);

                    presenter.getOwner(usableUris, {
                        success: function (owner) {
                            ownerChecked = true;
                            $(USERNAME, contents).
                                hpSearchCombo('set', owner);
                            $(SPINNER, contents).hide();
                            $(FORM_ITEMS, contents).show();
                            $(USERNAME_INPUT, contents).focus();
                        },
                        error: function (errorInfo) {
                            ownerChecked = true;
                            $(SPINNER, contents).hide();
                            $(FORM_ITEMS, contents).show();
                            $(USERNAME_INPUT, contents).focus();
                        }
                    });
                }

                formStateView.init({form: $(FORM, contents)});
                validator = $(FORM, contents).validate({
                    rules : {
                        alertAssignOwner : {required : true}
                    }
                });

                dialog = new DialogView({contents: contents,
                    ok: function () {
                        //to be removed once validator.js issue gets fixed
                        $(USERNAME, contents).on('change', onSelectChange);
                        if ($(FORM, contents).valid()) {
                            inProgress = false;
                            dialog = null;
                            presenter.assignUserToAlertByUris(usableUris, $(USERNAME).val());
                            formStateView.reset();
                            $(USERNAME, contents).off('change', onSelectChange);
                            return true;
                        } else {
                            return false;
                        }
                    },
                    cancel: function () {
                        inProgress = false;
                        dialog = null;
                        formStateView.reset();
                        $(USERNAME, contents).off('change', onSelectChange);
                    }
                });
                
                if (resultsForState.usable.length === 0) {
                    $(FORM_ITEMS).hide();
                    $(OK).hide();
                    $(CANCEL).text(localizer.getString('core.details.ok')).addClass(PRIMARY);
                    dialog.setMessage({summary: localizer.getString(
                        (resultsForState.ignore.length > 0) ? 
                            'fs.alerts.assign.none_assignable' : 'fs.alerts.show.selected_none')});
                } else if (resultsForState.ignore.length > 0) {
                    dialog.setMessage({summary:
                        localizer.getString('fs.alerts.assign.some_assignable')});                    
                }

                formStateView.reset();
                validator.resetForm();

                //to force the dialog to receive focus
                //since directly adding focus is not working.
                //todo: need to fix it in the future
                $(USERNAME_INPUT, contents).trigger('click');
            }

            this.show = function (uris) {
                if (!inProgress) {
                    inProgress = true;
                    showDialog(uris);
                }
            };
        }

        return new AlertAssignView();
    }());

    return AlertAssignView;
});
