"use strict";
(function ($) {
    $.field_servicewithprice = function (element, options) {
        var defaults = {
            values:[],
            item_service:'',
            max_service:1,
            price_service_field_name:'',
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element), 
            element = element;
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.list-service').select2();
            $element.find('.price-service').autoNumeric('init', {aSign: "$ "});

            $element.find('.btn-add-service').on('click', function(e) {
                plugin.set_task_when_click();
            });

            $element.find('.wrapper-item-service').each(function (index, item) {
                plugin.init_event_service_item($(item))
            });

        };
        plugin.init_event_service_item = function ($item_service) {
            $item_service.find('.btn-delete-service').click(function (e) {
                if ($element.find('.wrapper-item-service').length > 1) {
                    $item_service.remove();
                }
            })
        };
        plugin.set_task_when_click = function () {
            let max_service = plugin.settings.max_service;
            max_service = parseInt(max_service);
            let total_current_service = $element.find('.wrapper-item-service').length;
            if (total_current_service >= max_service) {
                $.alert({
                    title: 'Error',
                    content: `you cannot add more than ${max_service} `
                });
                return;
            }
            var $item_service = $(plugin.settings.item_service);
            $item_service.appendTo($element);
            $item_service.find('.list-service').select2();
            $item_service.find('.price-service').autoNumeric('init', {aSign: "$ "});
            $item_service.find('.btn-add-service').on('click',function (e) {
                plugin.set_task_when_click();
            });
            plugin.init_event_service_item($item_service);
        }
        plugin.example= function () {
        };
        plugin.init();
    }
    
    $.fn.field_servicewithprice = function (options) {
        
        return this.each(function () {
            
            if (undefined == $(this).data('field_servicewithprice')) {
                var plugin = new $.field_servicewithprice(this, options);
                $(this).data('field_servicewithprice', plugin);
            }
        });
    }
})(jQuery);