/*var FC = $.fullCalendar; // a reference to FullCalendar's root namespace
var View = FC.View;      // the class that all views must inherit from

var TeammateView = FC.ListView = View.extend({ // make a subclass of View

  initialize: function () {
    //console.log("initialize");

  },
  destroy: function() {
   //console.log('destroy ');
         // <your custom cleanup-code here>
         // call the super-class's method, forwarding all arguments
         //View.prototype.triggerViewDestroy.apply(this, arguments);
       },
       setHeight: function(height, isAuto) {
        //console.log('set height',height,isAuto);
        // responsible for adjusting the pixel-height of the view. if isAuto is true, the
        // view may be its natural height, and `height` becomes merely a suggestion.
        console.log('setHeight ');
      },
      destroyEvents: function() {
       // console.log('destroy events');
        $('.fc-event',this.el).remove();
          // responsible for undoing everything in renderEvents
        },
        render: function () {

         // console.log('render');
          var view = this;
            //if(this.el.find('.fc-teammate').length!=0) return;
            
            //Récuperation du squelette html de la vue
            view.el.addClass('fc-teammate-view').html( $('.planning-teammate-view').html());

            view.el.find('.fc-widget-content').sortable({
              handle: ".fc-teammate-label",
              axis: "y",
              update : function(){

                if(!view.options.views.teammate.sortTeammate) return;
                var sort = [];

                $('.fc-teammate-line:visible',view.el).each(function(i,tr){

                  sort.push($(tr).attr('data-teammate'));
                });
                view.options.views.teammate.sortTeammate(sort);
              },
              //permet de conserver la largeur des lignes lors du sort
              helper: function(e, tr)
              {
                var originals = tr.children();
                var helper = tr.clone();
                helper.children().each(function(index)
                {
                  $(this).width(originals.eq(index).width());
                });
                return helper;
              }
            });

            var teammates = view.options.views.teammate.teammates;

            //rendu des jours
            view.renderHeader();
            //rendu des equipiers
            view.renderTeammates(teammates);

            //evenements

            //ouverture de la modale de gesiton equipiers
            $('.btn-teammate-add',view.el).click(function(){
              $('#teammate-modal').modal();
              var teammates = view.options.views.teammate.teammates;
              var logins = [];
              for(var k in teammates){
               logins.push(teammates[k].login);
             }

              //Affichage des equipiers sélectionnés
              $('.teammate-picker input').each(function(i,input){
                var user = $(input).data();
                $(input).prop('checked',(logins.indexOf(user.login) !== -1)).trigger('change');
              });
            });

            //Sauvegarde des equipiers
            $('#teammate-modal .btn-save').click(function(){
              if(view.options.views.teammate.addTeammate){

                var teammates = [];
                var teammatesLogins = [];
                $('.teammate-picker input').each(function(i,input){
                 var user = $(input).data();
                 if($(input).prop('checked')){
                  teammates.push(user);
                  teammatesLogins.push(user.login);
                }
              });
                var response = view.options.views.teammate.addTeammate(teammatesLogins);
                if(response != false){
                  view.options.views.teammate.teammates = teammates;
                  $('#teammate-modal').modal('hide');
                }
              }
            });

          },
          setHeight: function (height, isAuto) {
            //console.log("setHeight"); 
          },

        //Rendu des lignes equipiers
        renderTeammates : function(teammates){
          var view = this;
          var bodyTable =  this.el.find('.fc-widget-content');
          $('.fc-teammate-line').remove();
          for(var k in teammates){
            var user = teammates[k];
            var current = moment(this.start).add(-1 , 'days'); 
            html = '<tr class="fc-teammate-line" data-teammate="'+user.login+'">';
            html += '<td class="fc-teammate-label"><div class="media"><img class="avatar avatar-mini avatar-rounded align-self-center mr-2" src="'+user.avatar+'"><span class="media-body">'+user.firstname+' '+user.name+'</span></div></td>';
            for(i=0;i<7;i++){
             current.add(1 , 'days');
             html+= '<td class="fc-day fc-widget-content fc-'+current.format('dd')+' '+(current.format('DD-MM-YYYY') == moment().format('DD-MM-YYYY') ? 'fc-today' :'') +'" data-date="'+current.format('YYYY-MM-DD')+'"><div class="morning"></div><div class="afternoon"></div></td>';
           }
           html += '</tr>';
           bodyTable.append(html);
         }

         if(view.options.highlight) $(view.options.highlight).addClass('highlight');
       },
        //Rendu des jours dans l'en-tete tableau
        renderHeader : function(){
         var headTable =  this.el.find('.fc-head-container tr');
         var current = moment(this.start).add(-1 , 'days');
         for(i=0;i<7;i++){
           current.add(1 , 'days');
           headTable.append('<th class="fc-day-header fc-widget-header fc-'+current.format('dd')+'"><span>'+current.format('dddd Do')+'</span></th>');
         }
       },
        //rendu des cellules de jour pour chaque ligne equipier
        renderUserDate : function(){
          var teammates = this.options.views.teammate.teammates;
          for(var k in teammates){
            var user = teammates[k];
            var current = moment(this.start).add(-1 , 'days');
            var userLine = $('tr[data-teammate="'+user.login+'"]');
              //userLine.find('.fc-event').remove();
              for(i=0;i<7;i++){
                current.add(1 , 'days');
                var cell = userLine.find('td.fc-day:eq('+i+')');
                cell.attr('class','fc-day fc-widget-content fc-'+current.format('dd')+' '+(current.format('DD-MM-YYYY') == moment().format('DD-MM-YYYY') ? 'fc-today' :'') )
                .attr('data-date',current.format('YYYY-MM-DD'));

              }
            }
          },
        //rendu des évenements dans les cellules de jours equipiers
        renderEvents: function (events) {
          //console.log("renderEvents"); 

          var dailyEvents = [];

          var bodyTable =  this.el.find('.fc-widget-content');
          var headTable =  this.el.find('.fc-head-container tr');
          var teammates = this.options.views.teammate.teammates;

          var current = moment(this.start).add(-1 , 'days');
          for(i=0;i<7;i++){
            current.add(1 , 'days');
            var cell = headTable.find('.fc-day-header:eq('+(i)+')');
            cell.attr('class','fc-day-header fc-widget-header fc-'+current.format('dd')).find('span').html(current.format('dddd Do'));
          }

          this.renderUserDate();

          var view = this;
          if(view.options.dayClick){
            $('.fc-day .morning,.fc-day .afternoon').click(function(jsEvent){
             var day = $(this).parent();
             this.dayClick = view.options.dayClick;
             this.dayClick(moment(day.attr('data-date')+' '+ ($(this).hasClass('morning')? '00:00': '12:00')  ),jsEvent,view);
           });
          }
          this.el.find('.fc-day').css('backgroundColor','');
            //events
            for(var i in events){
              var event = events[i];

              if(event.rendering && event.rendering=='background'){
                this.el.find('.fc-day[data-date="'+event.start.format('YYYY-MM-DD')+'"]').css('backgroundColor',event.backgroundColor);
                continue;
              }
              
              htmlEvent = '<div data-id="'+event.id+'" data-group="'+event.group+'" \
              style="background-color:'+event.backgroundColor+';color:'+event.textColor+';border-color:'+event.borderColor+';" \
              class="fc-event fc-content pointer '+(!event.editable ?'event-readonly':'')+'" \
              title="'+event.title+'"><i class="far fa-user-circle"></i> '+event.title+'</div>';
              
              for (i=0;i<= event.end.diff(event.start, 'days');i++){
                current = moment(event.start).add(i, 'days');
                var cell = this.el.find('tr[data-teammate="'+event.planningOwner+'"] [data-date="'+current.format('YYYY-MM-DD')+'"]');
            
                var halfes = [];

                //si le jour est entre les deux dates on remplis après midi et matin

                if( event.start.format('D') == current.format('D') ){
                  if(event.start.format('H') < 12) halfes.push('morning');
                  if(event.start.format('H') >= 12 || event.start.format('D')<event.end.format('D') ) halfes.push('afternoon');

                }
                if(current.format('D') == event.end.format('D') ){
                  if(event.end.format('H') < 12) halfes.push('morning');
                  if(event.end.format('H') >= 12) halfes.push('afternoon');
                }

                if( event.start.format('D') < current.format('D')  && current.format('D') < event.end.format('D')){
                  halfes.push('morning');
                  halfes.push('afternoon');
                }

                //déduplique les matinée / après midi en double
                halfes = halfes.filter((item,index)=> halfes.indexOf(item) === index);

                for(var u in halfes){
                  var nodeEvent = $(htmlEvent);
                  nodeEvent.data('event',event);
                  cell.find('.'+halfes[u]).append(nodeEvent);

                    if(view.options.eventClick ){
                      nodeEvent.click(function(jsEvent){
                       this.eventClick = view.options.eventClick;
                       this.eventClick(event,jsEvent,view);
                     });
                    }

                    if(view.options.eventMouseover){
                      nodeEvent.mouseover(function(jsEvent){
                       this.eventMouseover = view.options.eventMouseover;
                       this.eventMouseover(event,jsEvent,view);
                     });
                    }



                }
                
                
                if(this.options.eventRender) this.options.eventRender(event, nodeEvent,this);

              }

              
              
              var view = this;

              $(".fc-event:not(.event-readonly)" ).draggable({
                  revert: "invalid", // when not dropped, the item will revert back to its initial position
                  containment: ".fc-body",
                  snap: ".afternoon,.morning",
                  cursor: "move"
              });
              $( ".afternoon,.morning" ).droppable({
                accept: ".fc-event",
                classes: {
                  "ui-droppable-active": "custom-state-active"
                },
                
                drop: function( event, ui ) {
                  $(this).append(ui.draggable.detach().css({
                    top : 0,
                    left : 0
                  }));

                  var date = $(this).closest('.fc-day').attr('data-date');
                  var event = ui.draggable.data('event');

                  if($(this).hasClass('morning')){
                    event.start = moment(date+' 08:00');
                    event.end = moment(date+' 11:59');
                  }else{
                    event.start = moment(date+' 12:01');
                    event.end = moment(date+' 17:00');
                  }
                  
                  event.teammate =  $(this).closest('.fc-teammate-line').attr('data-teammate');

                  if(view.options.eventDrop) view.options.eventDrop(event,null,function(){

                  });
               }
             });

              
            }
            if(view.options.eventAfterAllRender) view.options.eventAfterAllRender();
          }
        });

//Enregistrement de la classe de vue dans les vues fullcalendar
FC.views.teammate = TeammateView ; 
*/

const { sliceEvents, createPlugin, Calendar } = FullCalendar

const CustomViewConfig = {

  classNames: [ 'custom-view' ],
  content: function(props,callback) {
    console.log('content');

    //console.log(props);
    let segs = sliceEvents(props, true); // allDay=true

    var html = '';

    var view = $($('.planning-teammate-view').html());


    


    var data = { days : []};
    var current = moment(props.dateProfile.currentRange.start).add(-1 , 'days');
     for(i=0;i<7;i++){
       current.add(1 , 'days');
       view.find('.fc-head tr:eq(0)s').append('<th class="fc-day-header fc-widget-header fc-'+current.format('dd')+'"><span>'+current.format('dddd Do')+'</span></th>');
     }
  

    html = view.get(0).outerHTML;
 
    /*html +=
      '<div class="view-title">' +
        props.dateProfile.currentRange.start.toUTCString() +
      '</div>' +
      '<div class="view-events">' +
        segs.length + ' events:' +
        '<ul>' +
          segs.map(function(seg) {
            return seg.def.title + ' (' + seg.range.start.toUTCString() + ')'
          }).join('') +
        '</ul>' +
      '</div>'*/





    return { html: html }
  },
  didMount : function(data){
    console.log('didmount');

    console.log(data);
   /* //ouverture de la modale de gesiton equipiers
            $('.btn-teammate-add',view.el).click(function(){
              $('#teammate-modal').modal();
              var teammates = view.options.views.teammate.teammates;
              var logins = [];
              for(var k in teammates){
               logins.push(teammates[k].login);
             }

              //Affichage des equipiers sélectionnés
              $('.teammate-picker input').each(function(i,input){
                var user = $(input).data();
                $(input).prop('checked',(logins.indexOf(user.login) !== -1)).trigger('change');
              });
            });

            //Sauvegarde des equipiers
            $('#teammate-modal .btn-save').click(function(){
              if(view.options.views.teammate.addTeammate){

                var teammates = [];
                var teammatesLogins = [];
                $('.teammate-picker input').each(function(i,input){
                 var user = $(input).data();
                 if($(input).prop('checked')){
                  teammates.push(user);
                  teammatesLogins.push(user.login);
                }
              });
                var response = view.options.views.teammate.addTeammate(teammatesLogins);
                if(response != false){
                  view.options.views.teammate.teammates = teammates;
                  $('#teammate-modal').modal('hide');
                }
              }
            });*/

    
  },
  component: function(data){
    console.log('component');
    console.log(data);
  },
  /*dateProfileGeneratorClass: function(data){
    console.log('dateProfileGeneratorClass');
    console.log(data);
  },*/
  willUnmount: function(data){
    console.log('willUnmount');
    console.log(data);
  },
  //type: String,
  //component: ct,
  //buttonText: String,
 // buttonTextKey: String,
 // dateProfileGeneratorClass: ct,
 // usesMinMaxTime: Boolean,
  //didMount: ct,
  //willUnmount: ct

}

const TeammateViewPlugin = createPlugin({
  views: {
    teammate: CustomViewConfig
  }
})
