define([
    'jquery',
    'mage/calendar',
    'mage/validation'
], function ($) {
    'use strict';

    $.widget('filoblu.storelocator_appointment', {

        _create: function () {

            var self = this,
                form = self.element,
                submitButton = $('#appointment-submit',form),
                dateField = $('#appointment_date',form),
                timeSlotSelect = $('#appointment_time_slot',form),
                workingDays = self.options.workingDays,
                allTimeSlots = self.options.timeSlots,
                product_name = self.options.product_name,
                product_sku  = self.options.product_sku,
                product_price = self.options.product_price,
                product_image = self.options.product_image,
                availableDays = [];

            self.initDatepickerAppointment(dateField,self,workingDays,availableDays,allTimeSlots,timeSlotSelect);

            submitButton.on('click', function(e){
                e.preventDefault();
                if($('#booking-form').valid()){
                    self.ajaxSubmitAppointment(form,product_name,product_sku,product_price,product_image);
                }

            })
        },

        ajaxSubmitAppointment: function(form,product_name,product_sku,product_price,product_image) {
            var wishlistItemsPreformatted = [],
                messageContainer = form.siblings('#submit-success-section'),
                messageSuccess = messageContainer.children('.appointment-success'),
                messageError = messageContainer.children('.appointment-error');

            messageSuccess.hide();
            messageError.hide();
            messageError.empty();

            for(var i = 0; i < window.wishlistItems.length; ++i)
            {
                wishlistItemsPreformatted.push(window.wishlistItems[i]);
            }
            var wishlistItems = wishlistItemsPreformatted.join(';');

            $.ajax({
                showLoader: true,
                url: form.attr("action"),
                data: form.serialize() + '&product_name=' + product_name + '&product_sku=' + product_sku + '&product_price=' + product_price + '&product_image=' + product_image + '&wishlist_products=' + wishlistItems,
                type: "POST",
                dataType: 'json'
            }).done(function (response) {
                if (response.success) {
                    form.fadeOut();
                    form.siblings('.product-wrapper').fadeOut();
                    form.siblings('.wishlist-appointment').fadeOut();
                    messageSuccess.show();
                }
                else {
                    form.valid();
                    messageError.html(response.message);
                    messageError.show();
                }
            }).fail(function (response) {
                messageError.html(response.message);
                messageError.show();
            }).always(function () {
                messageContainer.fadeIn();
            });
        },

        initDatepickerAppointment: function(dateField,self,workingDays,availableDays,allTimeSlots,timeSlotSelect) {
            dateField.calendar({
                dayNamesShort: true,
                showTime: false,
                dateFormat: "dd/mm/yy",
                minDate:new Date(),
                onSelect: function(dateText) {
                    var dataRetrived = $.datepicker.parseDate( "dd/mm/yy", dateText ),
                        chosenDay = $.datepicker.formatDate("D",dataRetrived);

                    self.matchAvailableDates(chosenDay,workingDays,availableDays);
                    self.createTimeSlotsSelectOptions(allTimeSlots,availableDays,timeSlotSelect);
                }
            });
        },

        matchAvailableDates: function(chosenDay,workingDays,availableDays) {
            workingDays.forEach(function (item, index) {
                if (item.dayStr === chosenDay) {
                    availableDays.push(item);
                }
            });
        },

        createTimeSlotsSelectOptions: function(allTimeSlots,availableDays,timeSlotSelect) {
            var availableTime = [];
            availableDays.forEach(function (item, index) {
                if (item.period === '1') {
                    availableTime.push(allTimeSlots[item.dayStr])
                }
            });
            timeSlotSelect.empty();
            if ($.isArray(availableTime[0])) {
                availableTime[0].forEach(function (item, index) {
                    timeSlotSelect.append('<option value="' + item + '">' + item + '</option>')
                });
            } else {
                timeSlotSelect.append('<option value="">' + availableTime + '</option>')
            }

            timeSlotSelect.removeAttr('disabled');
            availableTime.splice(0);
            availableDays.splice(0);
        }



    });

    return $.filoblu.storelocator_appoinment;
});
