App.ScheduleView = Ember.Component.extend
  event_changed: (event)->
    if employee_shift = @get('globals.current_employee').store.peekRecord('employee-shift', event.id)
      return unless event.start and event.end
      employee_shift.set 'start_from', event.start
      employee_shift.set 'end_on', event.end
      employee_shift.save()
  editEvent: (id, callbacks)->
    if employee_shift = @get('globals.current_employee').store.peekRecord('employee-shift', id)
      @modal 'employee_shift',
        title_path: 'employee_shift.modal.title'
        destroy_text_path: 'employee_shift.modal.destroy_confirmation'
        model: employee_shift
        save: -> callbacks.save.call(@, employee_shift) if callbacks.save
        destroy_callback: -> callbacks.destroy.call(@, employee_shift) if callbacks.destroy
  classNames: ['schedule-view']

  didRender: -> @drawCalendar()
  drawCalendar: ->
    placeholder = @$('#schedule-placeholder')
    events = @get('globals.current_supplier.employee_shifts').filter((employee_shift) -> employee_shift.get('employee.active') ).map( (employee_shift)->employee_shift.get('calendar_event') )
    editable = !!@get('globals.current_employee.manager')
    fullCalendarOptions =
      header:
        left: 'prev,next,today'
        center: 'title'
        right: 'agendaDay,agendaWeek,month'
      selectable: editable
      selectHelper: editable
      editable: editable
      defaultView: 'agendaWeek'
      events: events
      timezone: 'UTC'
      eventDrop: @event_changed.bind(@)
      eventResize: @event_changed.bind(@)
      dayClick: (date, jsEvent, view)->
        jsEvent.preventDefault()
        if view.type is 'month'
          placeholder.fullCalendar('changeView', 'agendaDay')
          placeholder.fullCalendar('gotoDate', date)
        false
      eventClick: (event)=>
        return unless editable
        @editEvent event.id,
          save: (shift)->
            placeholder.fullCalendar('removeEvents', [event.id])
            placeholder.fullCalendar('renderEvent', shift.get('calendar_event'), true)
          destroy: (shift)->
            placeholder.fullCalendar('removeEvents', [event.id])
      timeFormat: 'H(:mm)'
      slotLabelFormat: 'H:mm'
      lang: moment.locale()
    if editable
      fullCalendarOptions.select = (start, end, jsEvent, view) =>
        return if view.type is 'month'
        format = 'dddd h:mm'
        @modal 'select_employee',
          ok: ->
            # this context is SelectEmployeeController
            if employee = @get('employee')
              shift = employee.store.createRecord 'employee-shift', start_from: start, end_on: end
              shift.set 'employee', employee
              shift.save().then ->
                placeholder.fullCalendar('renderEvent', shift.get('calendar_event'), true)
          header: t('employee_shift.time_window', start: start.format(format), end: end.format(format))

    placeholder.fullCalendar fullCalendarOptions
