<commit_before>app = require 'application'

BaseView = require 'lib/base_view'
EventSharingButtonView = require './pending_event_sharings_button'
Header = require './calendar_header'

helpers = require 'helpers'


module.exports = class CalendarView extends BaseView

    id: 'view-container'
    template: require './templates/calendarview'


    initialize: (@options) ->
        @eventCollection = @model.events

        @listenTo @eventCollection, 'add', @refreshOne
        @listenTo @eventCollection, 'reset', @refresh
        @listenTo @eventCollection, 'remove', @onRemove
        @listenTo @eventCollection, 'change', @refreshOne

        @calendarsCollection = app.calendars
        @listenTo @calendarsCollection, 'change', @onCalendarCollectionChange

        @eventSharingButtonView = new EventSharingButtonView
            collection: @model.pendingEventSharingsCollection
            document: @options.document

        @model = null


    render: ->
        super()
        @eventSharingButtonView.snap(@).render()


    afterRender: ->
        locale = moment.localeData()

        @cal = @$ '#alarms'
        @view = @options.view
        # set default date
        currDate = moment()
        currDate.year(@options.year)   if @options.year?
        currDate.month(@options.month) if @options.month?
        currDate.date(@options.date)   if @options.date? and @view isnt 'month'

        @cal.fullCalendar
            lang: window.app.locale
            header: false
            firstDay: 1 # first day of the week is monday
            height: "auto"
            defaultView: @view
            defaultDate: currDate
            viewRender: @onChangeView
            #i18n with momentjs.
            monthNames: locale._months
            monthNamesShort: locale._monthsShort
            dayNames: locale._weekdays
            dayNamesShort: locale._weekdaysShort
            buttonText:
                today: t('today')
                month: t('month')
                day:   t('day')

            # Display time in the cozy's user timezone.
            # time given by Fullcalendar are ambiguous moments,
            # with cozy's user timezone values.
            # Cf http://fullcalendar.io/docs/timezone/timezone/
            timezone: window.app.timezone
            timeFormat: '' # Setted in scheduleitem title.
            columnFormat:
                'month': 'dddd'

            axisFormat: 'H:mm'
            allDaySlot: true
            selectable: true
            selectHelper: false
            unselectAuto: false
            eventRender: @onEventRender
            select: @onSelect
            eventDragStop: @onEventDragStop
            eventDrop: @onEventDrop
            eventClick: @onEventClick
            eventResizeStop: @onEventResizeStop
            eventResize: @onEventResize
            handleWindowResize: false
            weekNumbers: true
            nextDayThreshold: "04:00:00"

        source = @eventCollection.getFCEventSource @calendarsCollection
        @cal.fullCalendar 'addEventSource', source

        @calHeader = new Header
            cal: @cal
            view: @view

        # Before displaying the calendar for the previous month, we make sure
        # that events are loaded.
        @calHeader.on 'prev', =>
            @clearViewComponents =>
                monthToLoad = @cal.fullCalendar('getDate').subtract(1, 'months')
                window.app.events.loadMonth monthToLoad, =>
                    @cal.fullCalendar 'prev'

        # Before displaying the calendar for the next month, we make sure that
        # events are loaded.
        @calHeader.on 'next', =>
            @clearViewComponents =>
                monthToLoad = @cal.fullCalendar('getDate').add(1, 'months')
                window.app.events.loadMonth monthToLoad, =>
                    @cal.fullCalendar 'next'

        @calHeader.on 'today', =>
            @clearViewComponents =>
                @cal.fullCalendar 'today'

        @calHeader.on 'month', =>
            view = @cal.fullCalendar 'getView'
            hash = view.intervalStart.format '[month]/YYYY/M'
            app.router.navigate hash, true

        @calHeader.on 'week', =>
            view = @cal.fullCalendar 'getView'
            hash = view.intervalStart.format '[week]/YYYY/M/DD'
            app.router.navigate hash, true

        @calHeader.on 'list', =>
            @clearViewComponents ->
                window.app.events.sort()
                app.router.navigate 'list', trigger:true

        @$('#alarms').prepend @calHeader.render().$el

        @handleWindowResize()
        debounced = _.debounce @handleWindowResize, 10
        $(window).resize (ev) -> debounced() if ev.target is window


    remove: ->
        @popover?.close()
        super


    handleWindowResize: (initial) =>

        if $(window).width() > 1000
            targetHeight = $(window).height() - 85

        else if $(window).width() > 600
            targetHeight = $(window).height() - 100

        else
            targetHeight = $(window).height() - 50

        @cal.fullCalendar 'option', 'height', targetHeight


    refresh: () ->
        @cal.fullCalendar 'refetchEvents'


    onCalendarCollectionChange: () ->
        @refresh()

    onRemove: (model) ->
        @cal.fullCalendar 'removeEvents', model.cid


    refreshOne: (model) =>

        return null unless model?

        data = model.toPunctualFullCalendarEvent()

        [fcEvent] = @cal.fullCalendar 'clientEvents', data.id
        if fcEvent?
            @cal.fullCalendar 'removeEvents', data.id

        if model.isRecurrent()
            view = @cal.fullCalendar 'getView'
            start = view.intervalStart
            end = view.intervalEnd
            events = model.getRecurrentFCEventBetween start, end
            @cal.fullCalendar 'renderEvent', event for event in events
        else
            @cal.fullCalendar 'renderEvent', data


    onChangeView: (view) =>
        @calHeader?.render()
        if @view isnt view.name
            @handleWindowResize()

        @view = view.name

        hash = view.intervalStart.format '[month]/YYYY/M'
        if @view is 'month'
            hash = view.intervalStart.format '[month]/YYYY/M'
        else if @view is 'agendaWeek'
            hash = view.intervalStart.format '[week]/YYYY/M/DD'

        app.router.navigate hash
<commit_msg>Make code more explicit in add event code<commit_after>app = require 'application'

BaseView = require 'lib/base_view'
EventSharingButtonView = require './pending_event_sharings_button'
Header = require './calendar_header'

helpers = require 'helpers'


module.exports = class CalendarView extends BaseView

    id: 'view-container'
    template: require './templates/calendarview'


    initialize: (@options) ->
        @eventCollection = @model.events

        @listenTo @eventCollection, 'add', @refreshOne
        @listenTo @eventCollection, 'reset', @refresh
        @listenTo @eventCollection, 'remove', @onRemove
        @listenTo @eventCollection, 'change', @refreshOne

        @calendarsCollection = app.calendars
        @listenTo @calendarsCollection, 'change', @onCalendarCollectionChange

        @eventSharingButtonView = new EventSharingButtonView
            collection: @model.pendingEventSharingsCollection
            document: @options.document

        @model = null


    render: ->
        super()
        @eventSharingButtonView.snap(@).render()


    afterRender: ->
        locale = moment.localeData()

        @cal = @$ '#alarms'
        @view = @options.view
        # set default date
        currDate = moment()
        currDate.year(@options.year)   if @options.year?
        currDate.month(@options.month) if @options.month?
        currDate.date(@options.date)   if @options.date? and @view isnt 'month'

        @cal.fullCalendar
            lang: window.app.locale
            header: false
            firstDay: 1 # first day of the week is monday
            height: "auto"
            defaultView: @view
            defaultDate: currDate
            viewRender: @onChangeView
            #i18n with momentjs.
            monthNames: locale._months
            monthNamesShort: locale._monthsShort
            dayNames: locale._weekdays
            dayNamesShort: locale._weekdaysShort
            buttonText:
                today: t('today')
                month: t('month')
                day:   t('day')

            # Display time in the cozy's user timezone.
            # time given by Fullcalendar are ambiguous moments,
            # with cozy's user timezone values.
            # Cf http://fullcalendar.io/docs/timezone/timezone/
            timezone: window.app.timezone
            timeFormat: '' # Setted in scheduleitem title.
            columnFormat:
                'month': 'dddd'

            axisFormat: 'H:mm'
            allDaySlot: true
            selectable: true
            selectHelper: false
            unselectAuto: false
            eventRender: @onEventRender
            select: @onSelect
            eventDragStop: @onEventDragStop
            eventDrop: @onEventDrop
            eventClick: @onEventClick
            eventResizeStop: @onEventResizeStop
            eventResize: @onEventResize
            handleWindowResize: false
            weekNumbers: true
            nextDayThreshold: "04:00:00"

        source = @eventCollection.getFCEventSource @calendarsCollection
        @cal.fullCalendar 'addEventSource', source

        @calHeader = new Header
            cal: @cal
            view: @view

        # Before displaying the calendar for the previous month, we make sure
        # that events are loaded.
        @calHeader.on 'prev', =>
            @clearViewComponents =>
                monthToLoad = @cal.fullCalendar('getDate').subtract(1, 'months')
                window.app.events.loadMonth monthToLoad, =>
                    @cal.fullCalendar 'prev'

        # Before displaying the calendar for the next month, we make sure that
        # events are loaded.
        @calHeader.on 'next', =>
            @clearViewComponents =>
                monthToLoad = @cal.fullCalendar('getDate').add(1, 'months')
                window.app.events.loadMonth monthToLoad, =>
                    @cal.fullCalendar 'next'

        @calHeader.on 'today', =>
            @clearViewComponents =>
                @cal.fullCalendar 'today'

        @calHeader.on 'month', =>
            view = @cal.fullCalendar 'getView'
            hash = view.intervalStart.format '[month]/YYYY/M'
            app.router.navigate hash, true

        @calHeader.on 'week', =>
            view = @cal.fullCalendar 'getView'
            hash = view.intervalStart.format '[week]/YYYY/M/DD'
            app.router.navigate hash, true

        @calHeader.on 'list', =>
            @clearViewComponents ->
                window.app.events.sort()
                app.router.navigate 'list', trigger:true

        @$('#alarms').prepend @calHeader.render().$el

        @handleWindowResize()
        debounced = _.debounce @handleWindowResize, 10
        $(window).resize (ev) -> debounced() if ev.target is window


    remove: ->
        @popover?.close()
        super


    handleWindowResize: (initial) =>

        if $(window).width() > 1000
            targetHeight = $(window).height() - 85

        else if $(window).width() > 600
            targetHeight = $(window).height() - 100

        else
            targetHeight = $(window).height() - 50

        @cal.fullCalendar 'option', 'height', targetHeight


    refresh: () ->
        @cal.fullCalendar 'refetchEvents'


    onCalendarCollectionChange: () ->
        @refresh()

    onRemove: (model) ->
        @cal.fullCalendar 'removeEvents', model.cid


    refreshOne: (model) =>
        return null unless model?

        # Removing / adding prevent display glitches that update don't handle
        # properly like full day or reccuring events.
        @removeEventFromView model
        @addEventToView model

    getFcEvent: (model) =>
        [fcEvent] = @cal.fullCalendar 'clientEvents', model.cid
        return fcEvent

    addEventToView: (model) =>
        if model.isRecurrent()
            @_addReccuringEventToView model
        else
            @addFcEventToView model.toPunctualFullCalendarEvent()

    addFcEventToView: (fcEvent) =>
        @cal.fullCalendar 'renderEvent', fcEvent

    _addReccuringEventToView: (model) =>
        fcView = @cal.fullCalendar 'getView'
        start = fcView.intervalStart
        end = fcView.intervalEnd.add 7, 'day'
        events = model.getRecurrentFCEventBetween start, end
        @addFcEventToView event for event in events

    removeEventFromView: (model) =>
        fcEvent = @getFcEvent model
        @cal.fullCalendar 'removeEvents', model.cid if fcEvent?

    onChangeView: (view) =>
        @calHeader?.render()
        if @view isnt view.name
            @handleWindowResize()

        @view = view.name

        hash = view.intervalStart.format '[month]/YYYY/M'
        if @view is 'month'
            hash = view.intervalStart.format '[month]/YYYY/M'
        else if @view is 'agendaWeek'
            hash = view.intervalStart.format '[week]/YYYY/M/DD'

        app.router.navigate hash

{'fraction_non_alphanumeric': 0.10118285240714232, 'fraction_numerical': 0.004143750470880735, 'mean_word_length': 1.9822511795102224, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 58, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5985131', 'n_tokens_mistral': 3664, 'n_tokens_neox': 3479, 'n_words': 859}