/*
INPUT: 
  * workspaceId
  * type ('Emails' or 'PhoneNumbers')
DESCRIPTION
The contact picker. In terms of stores, it will search either in `workspacesContactsEmails` or `workspacesContactsPhoneNumbers`, depending on the `type` parameter.
Once a selection is done, it will emit a `selection-done` event, with the `row` parameter containing the selected row.
The widget can also open a `bd/WorkspacesContacts` widget to edit the information, and star/unstar contacts thans `widgets.storeToggle`.
*/
define([
  "dojo/_base/declare"
, "dojo/topic"
, "dojo/on"

, "dijit/form/TextBox"
, "dijit/form/CheckBox"

, "put-selector/put"

, "hotplate/hotClientDojo/dgridWidgets/commonMixins"
, "hotplate/hotClientDojo/widgets/widgets"
, "hotplate/hotClientDojo/widgets/TempDialog"
, "hotplate/hotClientDojo/dgridWidgets/EditableList"
, "hotplate/hotClientDojo/widgets/StoreToggle"

, "hotplate/bd/WorkspacesContacts"

], function(
  declare
, topic
, on

, TextBox
, CheckBox

, put

, commonMixins
, widgets
, TempDialog
, EditableList
, StoreToggle

, WorkspacesContacts
){

  function formatInfo( i ){
    if( !i ) return '';
    return ( i.firstName ? i.firstName + ' ' : '' ) + ( i.middleName? i.middleName + ' ': '' ) + ( i.lastName ? i.lastName : '' );
  };

  function formatPhoneNumber( n ){
    if( !n ) return '';
    if( n.dialCode ) return '+' + n.dialCode + ' - ' + n.number;
    else return n.number;
  };

  var Picker = declare( [ EditableList ], {

    ownClass: 'workspaces-contacts-picker workspaces-contacts-list auto-grow-dgrid',

    editOnDoubleClick: false,

    ListConstructor: declare( [ commonMixins.FullOnDemandListNoDnd ], {

      renderRow: function( object, options ){
    
        var self = this;
        var contact = object._children.contactId;

        // Will render it depending on what's in the object: it might be a phone
        // number or an email address
        var shownInfo;
        if( typeof( object.email ) !== 'undefined' ){
          shownInfo = object.email;
        } else {
          shownInfo = formatPhoneNumber( object );
        }

        // Make up the row
        var row = put( 'div.row' );

        if( object.contactId == object.previousContactId ){

          put( row, 'span.edit', "" ); // Empty edit span
          put( row, 'span.fake-toggle-widget'); // empty star span

          var data = put( row, 'span.data' );

          put( data, 'span.info', {} );
          put( data, 'span.separator' );

          put( data, 'span.shown-info', shownInfo );
          //put( email, 'span.email-info', shownInfo );

          //put( data, email );
          put( data, 'span.separator' );

        } else {

          // Maybe do something with this
          var ticked = false;
          if( contact.isStarred) ticked = true;


          put( row, 'span.dijitIconEdit.edit', "" );

          var star = new StoreToggle({ 

            toggleField: 'isStarred',
            storeName: 'workspacesContactsIsStarred',
            storeParameters: {
              workspaceId: contact.workspaceId,
            },
            recordId: contact.id,

            ticked: ticked,
          } );
         
          // Add .with-linked-user if 
          if( contact.userId ){
            put( row, '.row-with-linked-user' )
          }
          
          put( row, star.domNode );
          var data = put( row, 'span.data' );
          put( data, 'span.info', formatInfo( contact ) );
          put( data, 'span.separator' );

          put( data, 'span.shown-info', shownInfo );
          put( data, 'span.separator' );          

          //var email = put( data, 'span.email' );
          //put( email, 'span.email-info', shownInfo );

          //put( data, email );

          // Get a reference to the starWidget in the row (for future destruction)
          // and start it up
          row.starWidget = star;
          star.startup();      
        }

        return row;
      },

      //sort: "surname",
      dndParams: { selfAccept: false, copyOnly: true },

    }),

    onlyStarredContacts: false,
    searchBox: '',

    EditingWidgetConstructor: WorkspacesContacts,

    ExtraWidgetConstructor: declare( [ widgets.DestroyableTemplatedContainer ], {
      templateString: '' +
        '<div>\n' +

        '  <label for="${id}_search">Search</label>\n' +
        '  <div id="${id}_searchContacts" data-dojo-attach-point="searchContactsWidget" data-dojo-type="dijit/form/TextBox" data-dojo-props="intermediateChanges:true"></div>\n' +

        '  <label for="${id}_starredFilter">Only starred contacts</label>\n' +
        '  <div id="${id}_starredFilter" data-dojo-attach-point="starredFilterWidget" data-dojo-type="dijit/form/CheckBox" value="On"></div>\n' +

        '</div>\n'+
        '',
    }),
    extraWidgetPosition: 'top',

    editingWidgetPlacement: 'dialog',
    multipleEditingAllowed: false,
    gutters: false,

    buttonsPosition: 'after', // or "top" or "bottom"
    buttonsLeftOffset: 25,

    _setFilters: function(){

      var self = this;

      var collection = self.store;

      this.onlyStarredContacts ?
        ( collection = collection.filter( { isStarred: true } ) ) :
        null;

      this.searchBox !== '' ?
        ( collection = collection.filter( { searchAll:  this.searchBox })) :
        null;

      //collection = collection.filter( { })

      self.listWidget.set('collection', collection);
    },



    refreshContactsWidget: function(){

      var self = this;

      if( self.listWidget._inRefresh ){ 
        self.scheduleRefresh = true;
      } else {
        self._setFilters();
      }

      self.own(

        self.listWidget.on( 'dgrid-refresh-complete,dgrid-error', function( e ){
          if( self.scheduleRefresh ){
            self.scheduleRefresh = false;
            self._setFilters();
          }

        })

      );

    },

    _selectionDone: function( row ){
      var self = this;

      console.log("IN SELECTIONDONE:", row );

      if( ! self.alreadyEmitted ){
        self.alreadyEmitted = true;
        self.emit( 'selection-done', { bubbles: false, row: row  } );
      }

    },

    postMixInProperties: function(){
      this.inherited(arguments);

      this.storeName = 'workspacesContacts' + this.type + 'Search';
      this.storeParameters =  { workspaceId: this.workspaceId };
    },

    postCreate: function(){
      this.inherited(arguments);

      var self = this;

      self.own( 

        topic.subscribe( 'storeRecordCreate,storeRecordRemove,storeRecordUpdate', function( from, message, remote ) {
          if( message.storeName === 'workspacesContacts') self.refreshContactsWidget();
        }),

        // If the status of the widget changes, 
        self.extraWidget.starredFilterWidget.on( 'click', function( e ){
          self.onlyStarredContacts = !! this.get( 'value' );
          self._setFilters();
        }),

        self.extraWidget.searchContactsWidget.on( 'change', function( e ){
          self.searchBox = e;
          self.refreshContactsWidget();
        }),
 
        // Trigger editing on SINGLE click. Note that clicking on the "edit" icon
        // won't trigger selection but editing
        on( self.listWidget, 'click', function( e ){
          var row = self.row( e );
          
          if( e.target.className == 'dijitIconEdit edit' ){

            self._editRow( row, new WorkspacesContacts({
              storeName: 'workspacesContacts',
            })); 

          } else if( e.target.parentElement.className != 'toggle') {
            self._selectionDone( row );
          }

        }),

        on( self.listWidget, 'keypress' , function( e ){
          var row = self.row( e );
          e.preventDefault();

          if( e.charCode == 13 ){
            var row = self.row( e );
            self._selectionDone( row );

          } else if( e.charCode == 101 ){
            var row = self.row( e );
            
            self._editRow( row, new WorkspacesContacts({
              storeName: 'workspacesContacts',
              storeParameters: self.storeParameters,
              recordId: row.data.contactId,
            })); 

          }
          
        })

      );


    },


  } );

  return declare( [ TempDialog ], {

    postCreate: function(){
      this.inherited(arguments);

      var self = this;

      self.set( 'title', self.type === 'Emails' ? "Lookup by email" : "Lookup by phone number" );

      var picker = self.picker = new Picker({
        type: this.type,
        workspaceId: this.workspaceId,
      });

      this.addChild( picker );
      picker.startup();

      picker.on( 'selection-done', function( e ){
        self.emit( 'selection-done', { bubbles: false, row: e.row } );
        self.hide();
      });
    },

  });

});