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

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

app.state.AppointmentCreate = function()
{
    var state = app.core.StateManager.createState( 'appointment-create' ),
        $content,
        acData = {};

    state.onEnter = function( p )
    {
        var groups = [],
            activeGroupId;

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

        function checkCategories()
        {
            var teamId = $content.find( '[data-id="select-team-id"]' ).first().val(),
                $categorySelect = $content.find( '[data-id="select-category-' + teamId + '"]' ).first(),
                categories = $categorySelect.val();

            if ( 0 === categories.length )
            {
                $categorySelect.get(0).setCustomValidity( 'Select at least one category.' );
            }
            else
            {
                $categorySelect.get(0).setCustomValidity( "" );
            }
        }

        function checkStartEndData()
        {
            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( "" );
                }

                /*
                $endDate.get(0).setCustomValidity( "" );
                $endTime.get(0).setCustomValidity( "" );
                */
                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() );
                }
            }
        }

        function autocompleteSubjectLookup()
        {
            var activeGroupId = $content.find( '[data-id="select-team-id"]' ).first().val();
            return acData.hasOwnProperty( 'subjects_' + activeGroupId ) ? acData[ 'subjects_' + activeGroupId ] : [];
        }

        function autocompleteLocationLookup()
        {
            var activeGroupId = $content.find( '[data-id="select-team-id"]' ).first().val();
            return acData.hasOwnProperty( 'locations_' + activeGroupId ) ? acData[ 'locations_' + activeGroupId ] : [];
        }

        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( res )
                    {
                        for ( var gi = 0; gi < res.teams.length; gi++ )
                        {
                            groups.push( new app.model.Group( res.teams[ gi ], res[ 'members_' + res.teams[ gi ].id ] ) );
                        }

                        app.core.View.setContent(
                            app.core.View.getTemplate( 'appointment-form', { teams : res.teams, groups : groups, currentProfile : app.model.SessionUser.getUserProfile() } )
                        );

                        activeGroupId = $content.find( '[data-id="select-team-id"]' ).first().val();

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

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

                        $content.find( '[data-id="btn-cancel"]' ).click( function()
                        {
                            app.core.Controller.rediret( '#/home' );
                        });

                        $content.find( '[data-id="btn-create"]' ).click( function()
                        {
                            checkCategories();
                            checkStartEndData();

                            var $form = $content.find( '[data-id="form-appointment"]' ).first(),
                                teamId,
                                appointmentState = $form.find( '[data-id="checkbox-appointment-state"]' ).first().is( ':checked' ) ? 'open' : null,
                                isValid = app.util.Form.bootstrapValidate( $form );

                            if ( isValid )
                            {
                                app.gui.PageLoader.show();
                                teamId = $form.find( '[data-id="select-team-id"]' ).first().val();
                                app.core.Rpc.call(
                                    'Appointment',
                                    'create',
                                    {
                                        teamId : teamId,
                                        categoryIds : $form.find( '[data-id="select-category-' + teamId + '"]' ).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(),
                                        frequency : $form.find( '[name="input-frequency"]:checked' ).first().val(),
                                        frequencyUnit : $form.find( '[data-id="select-frequency-unit"]' ).first().val(),
                                        frequencyNumRepetition : $form.find( '[data-id="select-frequency-num-repetition"]' ).first().val(),
                                        comment : $form.find( '[data-id="textarea-comment"]' ).val(),
                                        appointmentState : appointmentState,
                                        priceFactor : ( +$form.find( '[data-id="input-price-factor"]' ).first().val() ) * 100
                                    },
                                    function( res )
                                    {
                                        if ( res && res.hasOwnProperty( 'appointment' ) )
                                        {
                                            if ( appointmentState === 'open' )
                                            {
                                                app.core.View.toastSuccess( _lc( 'APPOINTMENT_SUCCESSFULLY_CREATED' ) );
                                            }
                                            else
                                            {
                                                app.core.View.toastSuccess( _lc( 'APPOINTMENT_DRAFT_SUCCESSFULLY_CREATED' ) );
                                                setTimeout( function()
                                                {
                                                    app.core.View.toastInfo( _lc( 'APPOINTMENT_DRAFT_SUCCESSFULLY_CREATED_NOTE' ) );
                                                }, 1500 )
                                            }
                                            app.core.Controller.redirect( '#/home' );
                                        }
                                    }
                                );
                            }

                        });

                        $content.find( '[data-id="select-team-id"]' ).first().change( function()
                        {
                            var groupId = $(this).val();

                            $content.find( '[data-type="section-category-selection"]' ).hide();
                            $content.find( '[data-id="section-category-selection-' + groupId + '"]' ).first().show();

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

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

                            updateMaxPossibleBookers();

                        });

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

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

                        $content.find( '[data-id="input-frequency-single"]' ).first().change( function()
                        {
                            if ( $(this).is( ':checked' ) )
                            {
                                $content.find( '[data-id="collapse-frequency-details"]' ).first().collapse( 'hide' );
                            }
                        });

                        $content.find( '[data-id="input-frequency-multiple"]' ).first().change( function()
                        {
                            if ( $(this).is( ':checked' ) )
                            {
                                $content.find( '[data-id="collapse-frequency-details"]' ).first().collapse( 'show' );
                            }
                        });
                        // Special validation rules

                        /*
                        // 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"]' ).first().change( function()
                        {
                            $content.find( '[data-id="input-end-date"]' ).first().val( $(this).val() );
                            $content.find( '[data-id="input-deadline-date"]' ).first().val( $(this).val() );

                            var momentStartDate = moment( $(this).val(), "YYYY-MM-DD" );
                            momentStartDate.subtract( '1', 'days' );

                            $content.find( '[data-id="input-deadline-reject-date"]' ).first().val( momentStartDate.format( 'YYYY-MM-DD' ) );
                        });
                        $content.find( '[data-id="input-start-time"]' ).first().change( function()
                        {
                            let $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(),
                                momentStart = app.util.Helper.getMomentFromInputDateAndTime( $startDate, $startTime ),
                                momentReject = momentStart.clone();

                            $content.find( '[data-id="input-end-time"]' ).first().val( momentStart.add( 1, 'hours' ).format( 'HH:mm' ) );
                            $content.find( '[data-id="input-deadline-time"]' ).first().val( $(this).val() );
                            momentReject.subtract( '1', 'hours' );
                            $content.find( '[data-id="input-deadline-reject-time"]' ).first().val( momentReject.format( 'HH:mm' ) );

                            $endDate.get(0).setCustomValidity( "" );
                            $endTime.get(0).setCustomValidity( "" );

                        });
                        $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()
                        {
                            checkStartEndData();
                        });
                        // end: start-/enddate

                        // start: deadline
                        $content.find( '[data-id="input-deadline-date"],[data-id="input-deadline-time"]' ).on( "input", function()
                        {
                            let $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

                        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;
};