/**
 * (c) by aheadware.com
 */

var app = app || {};
app.state = app.state || {};

app.state.AppointmentEdit= function()
{
    var state = app.core.StateManager.createState( 'appointment-edit' ),
        $content;

    state.onEnter = function( p )
    {
        var teams = null,
            team = null,
            groups = [],
            group = null,
            acData = {},
            isSerial = p.hasOwnProperty( 'serial' ) ? p.serial : false,
            appointment = null,
            appointmentId = p.id;

        $content = app.core.View.getContent();

        function autocompleteSubjectLookup()
        {
            return acData.hasOwnProperty( 'subjects_' + group.getId() ) ? acData[ 'subjects_' + group.getId() ] : [];
        }

        function autocompleteLocationLookup()
        {
            return acData.hasOwnProperty( 'locations_' + group.getId() ) ? acData[ 'locations_' + group.getId()  ] : [];
        }

        function updateMaxPossibleBookers()
        {
            var bookVal = $content.find( '[name="input-visibility"]:checked' ).first().val(),
                activeGroupId = $content.find( '[data-id="select-team-id"]' ).first().val(),
                categoryIds = null,
                group = null,
                $mbDiv = $content.find( '[data-id="max-bookers"]' ).first(),
                bookerIds = [];

            if ( 'visibility-category-only' === bookVal )
            {
                var members = [];

                for( var gi = 0; gi < groups.length; gi++ )
                {
                    if ( groups[ gi ].getId() == activeGroupId )
                    {
                        group = groups[ gi ];
                        break;
                    }
                }

                categoryIds = $content.find( '[data-id="select-category-' + group.getId() + '"]' ).first().val();
                members = group.getMembers();

                for ( var mi = 0; mi < members.length; mi++ )
                {
                    for ( var ci = 0; ci < categoryIds.length; ci++ )
                    {
                        if ( members[ mi ].isInGroupCourseCategoryId( categoryIds[ ci ] ) )
                        {
                            bookerIds.push( members[ mi ].getId() );
                            break;
                        }
                    }
                }
                $mbDiv.find( '[data-id="span-max-bookers"]' ).first().html( bookerIds.length );
                $mbDiv.show();
            }
            else
            {
                $mbDiv.hide();
            }
        }

        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Appointment',
            'getAutocompleteData',
            null,
            function( acd )
            {
                acData = acd;

                app.core.Rpc.call(
                    'Team',
                    'getTeamsForAppointmentCreation',
                    null,
                    function( res1 )
                    {
                        teams = res1.teams;

                        for ( var gi = 0; gi < teams.length; gi++ )
                        {
                            groups.push( new app.model.Group( teams[ gi ], res1[ 'members_' + res1.teams[ gi ].id ] ) );
                        }

                        app.core.Rpc.call(
                            'Appointment',
                            'getDetail',
                            {
                                appointmentId : appointmentId
                            },
                            function( res2 )
                            {
                                appointment = new app.model.Appointment( res2.appointment, res2.attendee_data );

                                for ( var ti = 0; ti < teams.length; ti++ ) {
                                    if ( teams[ ti ].id == appointment.getTeamId() ) {
                                        team = teams[ ti ];
                                        break;
                                    }
                                }

                                for ( var gi = 0; gi < groups.length; gi++ )
                                {
                                    if ( groups[ gi ].getId() == appointment.getTeamId() ) {
                                        group = groups[ gi ];
                                        break;
                                    }
                                }

                                app.core.View.setContent(
                                    app.core.View.getTemplate(
                                        'appointment-form-edit',
                                        {
                                            team: team,
                                            a: appointment,
                                            g : group,
                                            currentProfile : app.model.SessionUser.getUserProfile()
                                        }
                                    )
                                );

                                $content.find( '[data-id="input-subject"]' ).first().autocomplete( {
                                    lookup: autocompleteSubjectLookup()
                                });

                                $content.find( '[data-id="input-location"]' ).first().autocomplete( {
                                    lookup: autocompleteLocationLookup()
                                });

                                $content.find( '[name="category"]' ).change( function()
                                {
                                    updateMaxPossibleBookers();
                                });

                                $content.find( 'input[name="input-visibility"]' ).change( function()
                                {
                                    updateMaxPossibleBookers();
                                });

                                $content.find( '[data-id="btn-save"]' ).click( function()
                                {
                                    let $form = $content.find( '[data-id="form-appointment"]' ).first(),
                                        isValid = app.util.Form.bootstrapValidate( $form );

                                    if ( isValid )
                                    {
                                        app.gui.PageLoader.show();
                                        app.core.Rpc.call(
                                            'Appointment',
                                            'update',
                                            {
                                                processSerial : isSerial,
                                                appointmentId : appointmentId,
                                                categoryIds : $form.find( '[data-id="select-category-' + appointment.getTeamId() + '"]' ).first().val(),
                                                visibility : ( 'visibility-category-only' === $form.find( '[name="input-visibility"]:checked' ).first().val() ) ? app.model.Appointment.ENUM_VISIBLE_FOR_CATEGORIES : app.model.Appointment.ENUM_VISIBLE_FOR_ALL,
                                                subject : $form.find( '[data-id="input-subject"]' ).first().val(),
                                                startTime : app.util.Helper.getMomentFromInputDateAndTime(
                                                    $form.find( '[data-id="input-start-date"]' ).first(),
                                                    $form.find( '[data-id="input-start-time"]' ).first()
                                                ).unix(),
                                                endTime : app.util.Helper.getMomentFromInputDateAndTime(
                                                    $form.find( '[data-id="input-end-date"]' ).first(),
                                                    $form.find( '[data-id="input-end-time"]' ).first()
                                                ).unix(),
                                                deadlineTime : app.util.Helper.getMomentFromInputDateAndTime(
                                                    $form.find( '[data-id="input-deadline-date"]' ).first(),
                                                    $form.find( '[data-id="input-deadline-time"]' ).first()
                                                ).unix(),
                                                deadlineRejectTime : app.util.Helper.getMomentFromInputDateAndTime(
                                                    $form.find( '[data-id="input-deadline-reject-date"]' ).first(),
                                                    $form.find( '[data-id="input-deadline-reject-time"]' ).first()
                                                ).unix(),
                                                location : $form.find( '[data-id="input-location"]' ).first().val(),
                                                //minAttendee : $form.find( '[data-id="select-min-attendee"]' ).first().val(),
                                                maxAttendee : $form.find( '[data-id="select-max-attendee"]' ).first().val(),
                                                comment : $form.find( '[data-id="textarea-comment"]' ).val(),
                                                resetAttendeeList : $form.find( '[data-id="checkbox-reset-attendee-list"]' ).first().is( ':checked' ) ? 'reset' : null,
                                                priceFactor : (+$form.find( '[data-id="input-price-factor"]' ).first().val()) * 100
                                            },
                                            function( res )
                                            {
                                                if ( res && res.hasOwnProperty( 'appointment' ) )
                                                {
                                                    app.core.View.toastSuccess( _lc( 'APPOINTMENT_SUCCESSFULLY_UPDATED' ) );
                                                    app.core.Controller.redirect( '#/home' );
                                                }
                                            }
                                        );
                                    }

                                });

                                /*
                                // start: min/max attendee
                                $content.find( '[data-id="select-min-attendee"],[data-id="select-max-attendee"]' ).on( 'input', function()
                                {
                                    let $minSelect = $content.find( '[data-id="select-min-attendee"]' ).first(),
                                        $maxSelect = $content.find( '[data-id="select-max-attendee"]' ).first();


                                    if ( $minSelect.val() != "0" &&
                                        $maxSelect.val() != "0" &&
                                        $minSelect.val() > $maxSelect.val() )
                                    {
                                        $minSelect.get(0).setCustomValidity( "Cannot be higher than max." );
                                        $maxSelect.get(0).setCustomValidity( "Cannot be lower than min." );
                                    }
                                    else
                                    {
                                        $minSelect.get( 0 ).setCustomValidity( '' );
                                        $maxSelect.get( 0 ).setCustomValidity( '' );
                                    }
                                });
                                // stop: min/max attendee
                                */

                                // start: start-/enddate
                                $content.find( '[data-id="input-start-date"],[data-id="input-start-time"],[data-id="input-end-date"],[data-id="input-end-time"]' ).on( 'input', function()
                                {
                                    var $startDate = $content.find( '[data-id="input-start-date"]' ).first(),
                                        $startTime = $content.find( '[data-id="input-start-time"]' ).first(),
                                        $endDate = $content.find( '[data-id="input-end-date"]' ).first(),
                                        $endTime = $content.find( '[data-id="input-end-time"]' ).first(),
                                        $deadlineDate = $content.find( '[data-id="input-deadline-date"]' ).first(),
                                        $deadlineTime = $content.find( '[data-id="input-deadline-time"]' ).first(),
                                        momentNow = moment(),
                                        momentStart = app.util.Helper.getMomentFromInputDateAndTime( $startDate, $startTime ),
                                        momentEnd = app.util.Helper.getMomentFromInputDateAndTime( $endDate, $endTime ),
                                        momentDeadline = app.util.Helper.getMomentFromInputDateAndTime( $deadlineDate, $deadlineTime );


                                    if ( momentNow.isAfter( momentStart ) )
                                    {
                                        $startDate.get(0).setCustomValidity( "Cannot be in past" );
                                        $startTime.get(0).setCustomValidity( "Cannot be in past!" );
                                    }
                                    else
                                    {
                                        $startDate.get(0).setCustomValidity( "" );
                                        $startTime.get(0).setCustomValidity( "" );

                                        if ( momentStart.isAfter( momentEnd ) )
                                        {
                                            $endDate.get(0).setCustomValidity( "Start cannot be after end." );
                                            $endTime.get(0).setCustomValidity( "Start cannot be after end." );
                                        }
                                        else
                                        {
                                            $endDate.get(0).setCustomValidity( "" );
                                            $endTime.get(0).setCustomValidity( "" );
                                        }

                                        // Update deadline
                                        if ( momentDeadline.isAfter( momentStart ) )
                                        {
                                            $content.find( '[data-id="input-deadline-date"]' ).first().val( $startDate.val() );
                                            $content.find( '[data-id="input-deadline-time"]' ).first().val( $startTime.val() );
                                        }
                                    }
                                });
                                // end: start-/enddate

                                // start: deadline
                                $content.find( '[data-id="input-deadline-date"],[data-id="input-deadline-time"]' ).on( "input", function()
                                {
                                    var $startDate = $content.find( '[data-id="input-start-date"]' ).first(),
                                        $startTime = $content.find( '[data-id="input-start-time"]' ).first(),
                                        $deadlineDate = $content.find( '[data-id="input-deadline-date"]' ).first(),
                                        $deadlineTime = $content.find( '[data-id="input-deadline-time"]' ).first(),
                                        momentStart = app.util.Helper.getMomentFromInputDateAndTime( $startDate, $startTime ),
                                        momentDeadline = app.util.Helper.getMomentFromInputDateAndTime( $deadlineDate, $deadlineTime );

                                    if ( momentDeadline.isAfter( momentStart ) )
                                    {
                                        $deadlineDate.get( 0 ).setCustomValidity( "Deadline cannot be past start time" );
                                        $deadlineTime.get( 0 ).setCustomValidity( "Deadline cannot be past start time" );
                                    }
                                    else
                                    {
                                        $deadlineDate.get( 0 ).setCustomValidity( "" );
                                        $deadlineTime.get( 0 ).setCustomValidity( "" );
                                    }
                                });
                                // stop: deadline

                                updateMaxPossibleBookers();

                                app.gui.PageLoader.hide();
                            }
                        );
                    }
                );
            }
        );
    };

    state.onExit = function( p )
    {
        $content.find( '[data-id="input-subject"]' ).first().autocomplete( 'dispose' );
        $content.find( '[data-id="input-location"]' ).first().autocomplete( 'dispose' );

        app.gui.Clockpicker.destroyForContent();
    };

    return state;
};