"use strict";
(function ($) {
    $.field_calendardatetime = function (element, options) {
        var defaults = {
            field_name: "",
            field_name_date_start_recurring:"",
            field_name_time_start_recurring:"",
            field_name_date_end_recurring:"",
            field_name_time_end_recurring:"",
            field_name_is_recurring:"",
            field_name_type_recurring:"",
            field_name_number_week_recurring:'',
            field_name_number_month_recurring:'',
            service_item: ""
        };
        let plugin = this;
        plugin.settings = {};
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let service_item = plugin.settings.service_item;
            let now = new Date();


            $element.find("#datetimepicker1").datetimepicker({
                inline: true,
                sideBySide: true,
                minDate: moment(),
                format : 'YYYY-MM-DD HH:mm'
            }).on('dp.change', function (e) {
                $element.find(`input[name="${plugin.settings.field_name}"]`).val(moment(e.date).format('YYYY-MM-DD HH:mm:ss')).trigger('change');
            });

            $element.find('input.date-start-recurring').daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                minYear: 1970,
                locale: {
                    format: 'YYYY-MM-DD'
                },
                maxYear: '+10',
                minDate: now
            }, function (start, end, label) {
                var years = moment().diff(start, 'years');
                $(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(start.format('YYYY-MM-DD'));
                let type_recurring = $element.find(`input[name="${plugin.settings.field_name_type_recurring['0']}"]:checked`).val();
                let number_week = $element.find(`input[name="${plugin.settings.field_name_number_week_recurring['0']}"]`).val();
                let number_month = $element.find(`input[name="${plugin.settings.field_name_number_month_recurring['0']}"]`).val();

                if(type_recurring === 'weekly') {
                    let duration_week = moment (start, 'YYYY-MM-DD').add(number_week, 'w');
                    plugin.setDateLinkOrther(duration_week);

                } else if (type_recurring === 'monthly') {
                    let duration_month = moment (start, 'YYYY-MM-DD').add(number_month, 'M');
                    plugin.setDateLinkOrther(duration_month);

                } else if( type_recurring === 'daily') {
                    let duration_day = moment (start, 'YYYY-MM-DD').add(1, 'd');
                    plugin.setDateLinkOrther(duration_day);
                }

            });
            $element.find('input.date-end-recurring').daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                minYear: 1970,
                locale: {
                    format: 'YYYY-MM-DD'
                },
                maxYear: '+10',
                minDate: now
            }, function (start, end, label) {
                var years = moment().diff(start, 'years');
                $(`input[name="${plugin.settings.field_name_date_end_recurring['0']}"]`).val(start.format('YYYY-MM-DD'));
            });
            $element.find('input.time-start-recurring').datetimepicker({
                format: 'HH:mm',
                disabledHours:[0]
            }).on('dp.change', function (e) {
                $element.find(`input[name="${plugin.settings.field_name_time_start_recurring['0']}"]`).val(moment(e.date).format('HH:mm:ss')).trigger('change');
                $element.find(`input[name="${plugin.settings.field_name_time_end_recurring['0']}"]`).val(moment(e.date).add(service_item.duration,'h').format('HH:mm:ss')).trigger('change');
                $element.find('input.time-end-recurring').val(moment(e.date).add(service_item.duration,'h').format('HH:mm'));
            });
            $element.find('input.time-end-recurring').datetimepicker({
                format: 'HH:mm',
                disabledHours:[0]
            }).on('dp.change', function (e) {
                $element.find(`input[name="${plugin.settings.field_name_time_end_recurring['0']}"]`).val(moment(e.date).format('HH:mm:ss')).trigger('change');
            });
            $element.find(`input[name="${plugin.settings.field_name_is_recurring['0']}"]`).on('change', function () {
                let $block_add_recurring = $element.find('.block-add-recurring');
                let $day_off_week = $block_add_recurring.find('.day-off-week');
                let $block_number_week_recurring = $block_add_recurring.find('.block-number-week-recurring');
                let $block_number_month_recurring = $block_add_recurring.find('.block-number-month-recurring');
                let now = new Date();
                if($(this).val() === "1") {
                    $element.find('.block-add-recurring').slideDown();
                    $element.find('input#rad-daily').prop('checked', true);
                    $element.find(`input[name="${plugin.settings.field_name}"]`).val('');
                    $element.find('input.time-booking').val('');
                    $element.find(".form_datetime").hide();
                    $element.find('input.date-start-recurring').val(moment(now).format('YYYY-MM-DD'));
                    $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(moment(now).format('YYYY-MM-DD'));
                    let min_duration_day = moment (now,'YYYY-MM-DD').add(1,'d');
                    plugin.setDateLinkOrther(min_duration_day);
                } else {
                    $element.find('.block-add-recurring').slideUp();
                    $element.find(".form_datetime").show();
                    $element.find('input[type="checkbox"]').prop('checked',false);
                    $block_add_recurring.find('input[type="radio"]').prop('checked',false);
                    $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val('');
                    $element.find(`input[name="${plugin.settings.field_name_date_end_recurring['0']}"]`).val('');
                    $day_off_week.slideUp();
                    $block_number_week_recurring.slideUp();
                    $block_number_month_recurring.slideUp();
                }
            });


            $element.find(`input[name="${plugin.settings.field_name_type_recurring['0']}"]`).on('change', function () {
                let $block_add_recurring = $(this).closest('.block-add-recurring');
                let $day_off_week = $block_add_recurring.find('.day-off-week');
                let $block_number_week_recurring = $block_add_recurring.find('.block-number-week-recurring');
                let $block_number_month_recurring = $block_add_recurring.find('.block-number-month-recurring');
                let now = new Date();
                if($(this).val() === "daily") {
                    $block_add_recurring.find('input[type="checkbox"]').prop('checked', false);
                    $day_off_week.slideUp();
                    $block_number_week_recurring.slideUp();
                    $block_number_week_recurring.find('input[type="text"]').val('');
                    $block_number_month_recurring.slideUp();
                    $block_number_month_recurring.find('input[type="text"]').val('');
                    $element.find('input.date-end-recurring').prop('disabled', false);
                    let min_duration_day = moment (now,'YYYY-MM-DD').add(1,'d');
                    $element.find('input.date-start-recurring').val(moment(now).format('YYYY-MM-DD'));
                    $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(moment(now).format('YYYY-MM-DD'));
                    plugin.setDateLinkOrther(min_duration_day);
                    $element.find('.block-select-allday').hide();
                    $element.find('.block-specific-day-select').hide();
                    $element.find('.block-specific-day-select .wrapper-day-specific').remove();
                    $element.find('.block-specific-day-select input[type="checkbox"]').prop('checked', false);
                    $element.find('.day-off-week input[type="checkbox"]').trigger('change');
                } else if ($(this).val() === "weekly") {
                    $day_off_week.slideDown();
                    $block_number_week_recurring.slideDown();
                    $block_number_month_recurring.slideUp();
                    $block_number_month_recurring.find('input[type="text"]').val('');
                    $block_number_week_recurring.find('input[type="text"]').val(1);
                    let min_duration_week = moment (now,'YYYY-MM-DD').add(7,'d');
                    $element.find('input.date-start-recurring').val(moment(now).format('YYYY-MM-DD'));
                    $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(moment(now).format('YYYY-MM-DD'));
                    plugin.setDateLinkOrther(min_duration_week);
                    $element.find('input.date-end-recurring').prop('disabled', true);
                    $element.find('.block-select-allday').hide();
                    $element.find('.block-specific-day-select').hide();
                    $element.find('.block-specific-day-select input[type="checkbox"]').prop('checked', false);
                } else if ($(this).val() === "monthly") {
                    $day_off_week.slideDown();
                    $block_number_week_recurring.slideUp();
                    $block_number_week_recurring.find('input[type="text"]').val('');
                    $block_number_month_recurring.find('input[type="text"]').val(1);
                    $block_number_month_recurring.slideDown();
                    let min_duration_month = moment (now, 'YYYY-MM-DD').add(1, 'M');
                    $element.find('input.date-start-recurring').val(moment(now).format('YYYY-MM-DD'));
                    $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(moment(now).format('YYYY-MM-DD'));
                    plugin.setDateLinkOrther(min_duration_month);
                    $element.find('input.date-end-recurring').prop('disabled', true);
                    $element.find('.block-select-allday').show();
                    $element.find('.block-select-allday .all-day-item:first-child input[type="radio"]').prop('checked', true);

                }
            });
            $element.find(`input[name="${plugin.settings.field_name_number_week_recurring['0']}"]`).on('change', function () {
                let number_week = $(this).val();
                if(number_week === '' || number_week < 0) {
                    $(this).val(1);
                    number_week=1;
                } else if (number_week > 30) {
                    $(this).val(30);
                    number_week=30;
                }
                let duration_week = moment (now,'YYYY-MM-DD').add(number_week,'w');
                $element.find('input.date-start-recurring').val(moment(now).format('YYYY-MM-DD'));
                $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(moment(now).format('YYYY-MM-DD'));
                plugin.setDateLinkOrther(duration_week);
            });
            $element.find(`input[name="${plugin.settings.field_name_number_month_recurring['0']}"]`).on('change', function () {
                let number_month = $(this).val();
                if(number_month === '' || number_month < 0) {
                    $(this).val(1);
                    number_month=1;
                } else if (number_month > 12) {
                    $(this).val(12);
                    number_month=12;
                }
                let duration_month = moment (now,'YYYY-MM-DD').add(number_month,'M');
                $element.find('input.date-start-recurring').val(moment(now).format('YYYY-MM-DD'));
                $element.find(`input[name="${plugin.settings.field_name_date_start_recurring['0']}"]`).val(moment(now).format('YYYY-MM-DD'));
                plugin.setDateLinkOrther(duration_month);
            });
        };

        plugin.getDayAnDateInMonth = function (date_start, date_end) {
            let arr_date1 = plugin.getDaysInMonth(date_start.split('-')['1'] - 1,date_start.split('-')['0']);
            let arr_date2 = plugin.getDaysInMonth(date_end.split('-')['1'] - 1,date_end.split('-')['0']);
            var weekday=new Array(7);
            weekday[0]="Sunday";
            weekday[1]="Monday";
            weekday[2]="Tuesday";
            weekday[3]="Wednesday";
            weekday[4]="Thursday";
            weekday[5]="Friday";
            weekday[6]="Saturday";
            let day_in_arr_date1 = arr_date1.map(value => weekday[value.getDay()]);
            let date_in_arr_date1 = arr_date1.map(value => moment(value).format('YYYY-MM-DD'));
            let day_in_arr_date2 = arr_date2.map(value => weekday[value.getDay()]);
            let date_in_arr_date2 = arr_date2.map(value => moment(value).format('YYYY-MM-DD'));
            let arrayDay = [];
            let array_day_in =[];
            let array_date_in = [];
            for(let i = 0; i< date_in_arr_date1.length; i++) {
                if(moment(date_start).valueOf() <= moment(date_in_arr_date1[i]).valueOf()) {
                    array_date_in.push(date_in_arr_date1[i]);
                    array_day_in.push(day_in_arr_date1[i])
                }
            }
            for(let i = 0; i< date_in_arr_date2.length; i++) {
                if(moment(date_end).valueOf() >= date_in_arr_date2[i]) {
                    array_date_in.push(date_in_arr_date2[i]);
                    array_day_in.push(day_in_arr_date2[i])
                }
            }
            arrayDay.push(array_day_in);
            arrayDay.push(array_date_in);
            return arrayDay;
        }

        plugin.getDaysInMonth = function (month, year) {
            var date = new Date(year, month, 1);
            var days = [];
            while (date.getMonth() === month) {
                days.push(new Date(date));
                date.setDate(date.getDate() + 1);
            }
            return days;
        };
        plugin.setDateLinkOrther = function (duration) {
            $element.find('input.date-end-recurring').data('daterangepicker').minDate = duration;
            $element.find('input.date-end-recurring').data('daterangepicker').startDate = duration;
            $element.find('input.date-end-recurring').val(duration.format('YYYY-MM-DD'));
            $element.find(`input[name="${plugin.settings.field_name_date_end_recurring['0']}"]`).val(duration.format('YYYY-MM-DD'));
        }
        plugin.example_function = function () {
        };
        plugin.init();
    };

    $.fn.field_calendardatetime = function (options) {

        return this.each(function () {

            if (undefined === $(this).data('field_calendardatetime')) {
                var plugin = new $.field_calendardatetime(this, options);
                $(this).data('field_calendardatetime', plugin);
            }
        });
    }
})(jQuery);