/*
 * Copyright (c) 2013, TRIOLOGY GmbH
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * https://www.scm-manager.com
 *
 */

Triology.groupmanager.GroupManagerFormPanel = Ext.extend(Sonia.rest.FormPanel, {
  colMemberText : Triology.groupmanager.I18n.groupManagerText,
  membersText : Triology.groupmanager.I18n.groupManagerText,
  managerStore : null,
  addIcon : 'resources/images/add.png',
  removeIcon : 'resources/images/delete.png',
  errorTitleText : 'Error',
  updateErrorMsgText : 'Group-Manager update failed',
  createErrorMsgText : 'Group-Manager creation failed',
  
  // help
  nameHelpText : 'Unique name of the group.',
  descriptionHelpText : 'A short description of the group.',
  membersHelpText : 'Usernames of the group members.',
  

  initComponent : function() {
    this.addEvents('preCreate', 'created', 'preUpdate', 'updated', 'updateFailed', 'creationFailed');
    this.managerStore = new Ext.data.SimpleStore({
      fields : [ 'groupmanager' ],
      sortInfo : {
        field : 'groupmanager'
      }
    });

    var memberColModel = new Ext.grid.ColumnModel({
      defaults : {
        sortable : true
      },
      columns : [ {
        id : 'groupmanager',
        header : Triology.groupmanager.I18n.groupManagerText,
        dataIndex : 'groupmanager',
        editor : new Ext.form.ComboBox({
          store : userSearchStore,
          displayField : 'label',
          valueField : 'value',
          typeAhead : true,
          mode : 'remote',
          queryParam : 'query', // contents of the field sent to server.
          hideTrigger : true, // hide trigger so it doesn't look like a combobox.
          selectOnFocus : true,
          width : 250
        })
      } ]
    });

    var selectionModel = new Ext.grid.RowSelectionModel({
      singleSelect : true
    });

    if (this.item) {
      var data = [];
      if (this.item.groupmanager) {
        for ( var i = 0; i < this.item.groupmanager.length; i++) {
          var a = [];
          a.push(this.item.groupmanager[i]);
          data.push(a);
        }
      }
      this.managerStore.loadData(data);
    }

    var config = {
      title : this.membersText,
      listeners : {
        updated : this.clearModifications,
        preUpdate : {
          fn : this.updateGroupManager,
          scope : this
        }
      },
      items : [ {
        id : 'groupmanagerGrid',
        xtype : 'editorgrid',
        clicksToEdit : 1,
        frame : true,
        width : '100%',
        autoHeight : true,
        autoScroll : false,
        colModel : memberColModel,
        sm : selectionModel,
        store : this.managerStore,
        viewConfig : {
          forceFit : true
        },
        tbar : [ {
          text : this.addText,
          scope : this,
          icon : this.addIcon,
          handler : function() {
            var Member = this.managerStore.recordType;
            var grid = Ext.getCmp('groupmanagerGrid');
            grid.stopEditing();
            this.managerStore.insert(0, new Member());
            grid.startEditing(0, 0);
          }
        }, {
          text : this.removeText,
          scope : this,
          icon : this.removeIcon,
          handler : function() {
            var grid = Ext.getCmp('groupmanagerGrid');
            var selected = grid.getSelectionModel().getSelected();
            if (selected) {
              this.managerStore.remove(selected);
            }
          }
        }, '->', {
          id : 'groupmanagerGridHelp',
          xtype : 'box',
          autoEl : {
            tag : 'img',
            src : 'resources/images/help.png'
          }
        } ]
      } ]
    };

    Ext.apply(this, Ext.apply(this.initialConfig, config));
    Triology.groupmanager.GroupManagerFormPanel.superclass.initComponent.apply(this, arguments);
  },
  
  update : function(group) {
    if (debug) {
      console.debug('update group ' + group.name);
    }
    group = Ext.apply(this.item, group);

    this.fireEvent('preUpdate', group);

    var url = restUrl + 'groupmanager/' + group.name + '.json';
    var el = this.el;
    var tid = setTimeout(function() {
      el.mask('Loading ...');
    }, 100);

    Ext.Ajax.request({
      url : url,
      jsonData : group,
      method : 'PUT',
      scope : this,
      success : function() {
        if (debug) {
          console.debug('update success');
        }
        this.fireEvent('updated', group);
        clearTimeout(tid);
        el.unmask();
        this.execCallback(this.onUpdate, group);
      },
      failure : function(result) {
        this.fireEvent('updateFailed', group);
        clearTimeout(tid);
        el.unmask();
        main.handleRestFailure(result, this.errorTitleText, this.updateErrorMsgText);
      }
    });
  },

  create : function(item) {
    if (debug) {
      console.debug('create group: ' + item.name);
    }
    item.type = state.defaultUserType;

    var url = restUrl + 'groupmanager.json';
    var el = this.el;
    var tid = setTimeout(function() {
      el.mask('Loading ...');
    }, 100);

    this.fireEvent('preCreate', item);

    // this.updateMembers(item);

    Ext.Ajax.request({
      url : url,
      jsonData : item,
      method : 'POST',
      scope : this,
      success : function() {
        if (debug) {
          console.debug('create success');
        }
        this.fireEvent('created', item);
        // this.memberStore.removeAll();
        this.getForm().reset();
        clearTimeout(tid);
        el.unmask();
        this.execCallback(this.onCreate, item);
      },
      failure : function(result) {
        this.fireEvent('creationFailed', item);
        clearTimeout(tid);
        el.unmask();
        main.handleRestFailure(result, this.errorTitleText, this.createErrorMsgText);
      }
    });
  },

  cancel : function() {
    if (debug) {
      console.debug('cancel form');
    }
    Triology.groupmanager.setEditPanel(Triology.groupmanager.DefaultPanel);
  },

  afterRender : function() {
    // call super
    Triology.groupmanager.GroupManagerFormPanel.superclass.afterRender.apply(this, arguments);

    Ext.QuickTips.register({
      target : Ext.getCmp('groupmanagerGridHelp'),
      title : '',
      text : Triology.groupmanager.I18n.groupManagerHelpText,
      enabled : true
    });
  },

  updateGroupManager : function(item) {
    var managers = [];
    this.managerStore.data.each(function(record) {
      managers.push(record.data.groupmanager);
    });
    item.groupmanager = managers;
  },

  clearModifications : function() {
    Ext.getCmp('groupmanagerGrid').getStore().commitChanges();
  }

});

Ext.reg('groupManagerForm', Triology.groupmanager.GroupManagerFormPanel);
