// @flow
import template from './templates/membersSplitPanelEditor.html';
import MembersSplitController from './impl/membersSplit/controller/MembersSplitController';
import formRepository from '../formRepository';
import BaseLayoutEditorView from './base/BaseLayoutEditorView';
import WindowService from '../../services/WindowService';

// used as function because Localization service is not initialized yet
const defaultOptions = () => ({
    exclude: [],
    displayText: '',
    hideUsers: false,
    hideGroups: false,
    hideToolbar: false,
    maxQuantitySelected: null,
    allowRemove: true,
    title: '',
    itemsToSelectText: Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.USERSTOSELECT'),
    selectedItemsText: Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.SELECTEDUSERS'),
    searchPlaceholder: Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.SEARCHUSERS'),
    emptyListText: Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.EMPTYLIST'),
    users: undefined,
    groups: undefined,
    showMode: null,
    cacheService: undefined,
    getDisplayText: null
});

export default (formRepository.editors.MembersSplit = BaseLayoutEditorView.extend({
    initialize(options = {}) {
        _.defaults(this.options, _.pick(options.schema ? options.schema : options, Object.keys(defaultOptions())), defaultOptions());

        const defOps = Object.assign(defaultOptions(), {
            users: options.users ||
                options.cacheService.GetUsers().map(user => ({
                    id: user.Id,
                    name: user.Text || user.Username,
                    abbreviation: user.abbreviation,
                    userpicUri: user.userpicUri,
                    type: 'users'
                })),
            groups: options.groups ||
                options.cacheService.GetGroups().map(group => ({
                    id: group.id,
                    name: group.name,
                    type: 'groups'
                }))
        });

        _.defaults(this.options, _.pick(options.schema ? options.schema : options, Object.keys(defOps)), defOps);

        this.options.selected = this.getValue();

        this.controller = new MembersSplitController(this.options);
        if (this.getOption('showMode') !== 'button') {
            this.controller.on('popup:ok', () => {
                this.__value(this.options.selected, true);
            });
        }
    },

    className: 'member-split',

    focusElement: null,

    attributes: {
        tabindex: 0
    },

    regions: {
        splitPanelRegion: '.js-split-panel-region'
    },

    ui: {
        membersEditor: '.js-members-editor',
        membersText: '.js-members-text'
    },

    events: {
        'click @ui.membersEditor': '__showPopup'
    },

    template: Handlebars.compile(template),

    templateContext() {
        return {
            displayText: this.options.displayText,
            showButton: this.getOption('showMode') === 'button'
        };
    },

    setValue(value) {
        this.__value(value, false);
    },

    onRender() {
        if (this.getOption('showMode') !== 'button') {
            this.controller.initItems();

            this.showChildView('splitPanelRegion', this.controller.view);
        }
    },

    reloadCollection(users: Array<{ id: string, name: string }>, groups: Array<{ id: string, name: string }>): void {
        this.options.users = users;
        this.options.groups = groups;
        this.controller.fillInModel();
        this.controller.initItems();
    },

    __showPopup() {
        if (!this.getEnabled()) {
            return;
        }
        this.options.selected = this.getValue();
        this.controller.initItems();

        const popup = new Core.layout.Popup({
            size: {
                width: '980px',
                height: '700px'
            },
            header: this.getOption('title') || Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.MEMBERSTITLE'),
            buttons: [{
                id: 'save',
                text: Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.APPLY'),
                handler: () => {
                    this.controller.updateMembers();
                    this.__value(this.options.selected, true);
                    Core.services.WindowService.closePopup();
                }
            },
            {
                id: 'close',
                text: Localizer.get('CORE.FORM.EDITORS.MEMBERSPLIT.CANCEL'),
                handler: () => {
                    this.controller.cancelMembers();
                    Core.services.WindowService.closePopup();
                }
            }
            ],
            content: this.controller.view
        });

        WindowService.showPopup(popup);
    },

    __updateText() {
        this.ui.membersText.text(this.controller.getDisplayText());
    },

    __value(value, triggerChange) {
        if (this.getOption('showMode') === 'button') {
            this.__updateText();
        }
        this.value = value;

        if (triggerChange) {
            this.__triggerChange();
        }
    }
}));

@@ -1389,16 +1389,32 @@
   users:
+%0A               
  options
@@ -1749,16 +1749,32 @@
  groups:
+%0A               
  options
@@ -3986,18 +3986,39 @@
 ttons: %5B
-%7B
 %0A
+                %7B%0A    
         
@@ -4034,15 +4034,20 @@
 d: '
-save',%0A
+close',%0A    
     
@@ -4113,13 +4113,14 @@
 LIT.
-APPLY
+CANCEL
 '),%0A
@@ -4139,141 +4139,148 @@
     
-handler: () =%3E %7B%0A                    this.controller.updateMembers();%0A                    this.__value(this.options.selected, true);%0A
+    customClass: 'btn-small btn-outline',%0A                    handler: () =%3E %7B%0A                        this.controller.cancelMembers();%0A    
     
@@ -4345,34 +4345,42 @@
                 
+  
-%7D%0A
+  %7D%0A    
             %7D,%0A 
@@ -4382,32 +4382,36 @@
  %7D,%0A            
+    
 %7B%0A              
@@ -4408,33 +4408,36 @@
             
+ 
+   
 id: '
-clos
+sav
 e',%0A        
@@ -4436,32 +4436,36 @@
                 
+   
+ 
 text: Localizer.
@@ -4495,34 +4495,83 @@
 MEMBERSPLIT.
-CANCEL
+APPLY
 '),%0A
+                    customClass: 'btn-small',%0A    
             
@@ -4603,32 +4603,36 @@
                 
+    
 this.controller.
@@ -4623,38 +4623,38 @@
 this.controller.
-cancel
+update
 Members();%0A     
@@ -4640,32 +4640,103 @@
 pdateMembers();%0A
+                        this.__value(this.options.selected, true);%0A    
                 
@@ -4789,34 +4789,42 @@
                 
-%7D%0A
+    %7D%0A    
             %7D%0A  

fix member split editor