"use strict";
(function ($) {
    $.view_signup = function (element, options) {
        let defaults = {
            email_exist:'',
            username_exist:''
        };
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('form[name="signup_form"]').each(function (e) {
                $(this).validate({
                    ignore: "",
                    rules: {
                        password: {password :true },
                        user_name: {user_name: true},
                        first_name: {name_check: true},
                        last_name: {name_check: true},
                    },
                    messages:{
                        terms_and_privacy:'You must accept the Terms of Use & Privacy Policy to create account'
                    },
                    errorPlacement: function (error, element) {
                        switch (element.attr("id")) {
                            case 'first_name':
                                error.insertAfter(element);
                                break;
                            case 'last_name':
                                error.insertAfter(element);
                                break;
                            case 'user_name':
                                error.insertAfter(element);
                                break;
                            case 'email':
                                error.insertAfter(element);
                                break;
                            case 'password':
                                error.insertAfter(element);
                                break;
                            case 'terms_and_privacy':
                                error.insertAfter($(".content-terms"));
                                break;
                            default:
                            //nothing
                        }
                    }
                });
            });
            jQuery.validator.addMethod("user_name", function(value, element) {
                return this.optional(element) || /^[a-zA-Z0-9]([._](?![._])|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$/.test(value);
            }, "Username is 8-20 characters, first character is alphanum, contains no special characters except the underscore");
            jQuery.validator.addMethod("name_check", function(value, element) {
                return this.optional(element) || /([a-zA-Z',.-]+( [a-zA-Z',.-]+)*){2,30}/.test(value);
            }, "First character is alphanum");
            jQuery.validator.addMethod("password", function(value, element) {
                return this.optional(element) || /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(value);
            }, "Minimum 8 characters, at least 1 uppercase letter, 1 lowercase letter, 1 number and 1 special character");

            $element.find('.sign-up-button').on('click', function () {
                let  $form = $(this).closest('form[name="signup_form"]');
                let is_ok = false;
                let password = $form.find('input[name="password"]').val();
                let username = $form.find('input[name="user_name"]').val();
                let first_name = $form.find('input[name="first_name"]').val();
                let last_name = $form.find('input[name="last_name"]').val();
                let email = $form.find('input[name="email"]').val();
                let terms_and_privacy = $form.find('input[name="terms_and_privacy"]').val();
                if(first_name.trim()  !== '' || last_name.trim() !== '' || username.trim() !== '' || email.trim() !== '' || password.trim() !== '' || terms_and_privacy.trim() === '') {
                    is_ok = false;
                } else {
                    is_ok = true;
                }

                if (!$form.valid()) {
                    is_ok = false;
                } else {
                    is_ok= true;
                }

                if(plugin.settings.email_exist === false && plugin.settings.username_exist === false) {
                    is_ok = true;
                } else {
                    is_ok = false;
                }

                if(is_ok) {
                    $form.submit();
                }
            });

            var checkEmailExist = plugin.debounce(function () {
                var output = plugin.convert_data_form();
                let dataObj = {};
                $(output).each(function(i, field){
                    dataObj[field.name] = field.value[0];
                });
                $.ajax({
                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        dataObj: dataObj,
                        task: "signup.check_exist_email",
                    },
                    beforeSend: function() {
                        $('body').loadingModal();
                    },
                    success: function(res) {
                        res = JSON.parse(res)
                        let data = res.data;
                        plugin.settings.email_exist = data;
                        if(data) {
                            $element.find('.email-exist').show();
                            $element.find('.email-block i').hide();

                        } else {
                            $element.find('.email-exist').hide();
                            $element.find('.email-block i').show();
                        }
                    },
                    error: function(xhr) { // if error occured

                    },
                    complete: function() {
                        $('body').loadingModal('destroy');

                    },
                })

            }, 3000);
            var checkUsernameExist = plugin.debounce(function () {
                var output = plugin.convert_data_form();
                let dataObj = {};
                $(output).each(function(i, field){
                    dataObj[field.name] = field.value[0];
                });
                $.ajax({
                    url: wpbookingpro_root_url+wpbookingpro_api_task,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        dataObj: dataObj,
                        task: "signup.check_exist_username",
                    },
                    beforeSend: function() {
                        $('body').loadingModal();
                    },
                    success: function(res) {
                        res = JSON.parse(res)
                        let data = res.data;
                        plugin.settings.username_exist = data;
                        if(data) {
                            $element.find('.username-exist').show();
                            $element.find('.user-name-block i').hide();

                        } else {
                            $element.find('.username-exist').hide();
                            $element.find('.user-name-block i').show();
                        }
                    },
                    error: function(xhr) { // if error occured

                    },
                    complete: function() {
                        $('body').loadingModal('destroy');

                    },
                })

            }, 3000);

            $element.find('input[name="email"]').on('keyup', checkEmailExist);
            $element.find('input[name="user_name"]').on('keyup', checkUsernameExist);
        };

        plugin.debounce = function(func, wait) {
            var timeout;

            return function() {
                var context = this,
                    args = arguments;

                var executeFunction = function() {
                    func.apply(context, args);
                };

                clearTimeout(timeout);
                timeout = setTimeout(executeFunction, wait);
            };
        };
        plugin.convert_data_form = function() {
            var dataArray = $element.find('form[name="signup_form"]').serializeArray();
            var output = [];
            dataArray.forEach(function(item) {
                var existing = output.filter(function(v, i) {
                    return v.name == item.name;
                });
                if (existing.length) {
                    var existingIndex = output.indexOf(existing[0]);
                    output[existingIndex].value = output[existingIndex].value.concat(item.value);
                } else {
                    if (typeof item.value == 'string')
                        item.value = [item.value];
                    output.push(item);
                }
            });
            return output;
        };


        plugin.example_function = function () {
        }
        plugin.init();
    }
    $.fn.view_signup = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_signup')) {
                let plugin = new $.view_signup(this, options);
                $(this).data('view_signup', plugin);
            }
        });
    }
})(jQuery);
