;( function ( $ ) {
   
    // XD Local Storage
    xdLocalStorage.init(
        {
            iframeUrl: 'https://api.hasthemes.com/api/copypaste/index.html',
            initCallback: function () { /* if need any callback */ }
        }
    );

    function getUniqueId( elements ) {
        elements.forEach( function( item, index ) {
            item.id = elementorCommon.helpers.getUniqueId();
            if( item.elements.length > 0 ) {
                getUniqueId( item.elements );
            }
        } );
        return elements;
    }

    function importContent( newWidget, elementCode, container ) {

        var EncodedElementCode = JSON.stringify(elementCode);
        var hasMedia = /\.(png|jpg|jpeg|svg|gif|webp|tiff|psd|raw|bmp|heif)/gi.test(EncodedElementCode);

        if ( hasMedia ) {

            var model   = { 
                elType: newWidget.elType,
                settings: elementCode.settings,
                widgetType : newWidget.widgetType
            };

            var widgetSelector = $e.run('document/elements/create', {
                container: container,
                model    : model
            });

            $.ajax({
                url       : htmegacrosscp.ajaxurl,
                method    : 'POST',
                data      : {
                    action  : 'htmega_copy_paste_data',
                    data    : EncodedElementCode,
                    security: htmegacrosscp.nonce,
                },
                beforeSend: function () {
                    widgetSelector.view.$el.append('<div id="htmega-import-process" style="text-align:center;">Importing images..</div>');
                }
            }).done(function (response) {
                if ( response.success ) {
                    var data       = response.data[0];
                    model.settings = data.settings;
                    model.elType   = data.elType;
                    if ( 'widget' === data.elType ) {
                        model.widgetType = data.widgetType;
                    } else {
                        model.elements = data.elements;
                    }
                    setTimeout(function () {
                        $e.run('document/elements/delete', { 
                            container: widgetSelector 
                        });
                        $e.run('document/elements/create', {
                            model    : model,
                            container: container
                        });
                    }, 500 );
                    $('#htmega-import-process').remove();
                }
            }).fail(function(error){
                elementor.notifications.showToast({
                    message: elementor.translate('Something went wrong!')
                });
            });
        } else {
            $e.run( "document/elements/create", {
                model: newWidget,
                container: container,
            });
        }
    }

    function processImport( newElement, element ) {

        // Get element
        var getElementType = element.model.get( "elType" );
        
        // New Element
        if( typeof newElement.elementCode === 'object' ){
            var elementType = newElement.elementCode.elType;
            var elementCode = newElement.elementCode;
        } else {
            var elementType = newElement.elType;
            var elementCode = newElement;
        }

        
        var newWidget = {
            elType: elementType,
            settings: elementCode.settings
        };
        var container;

        switch( elementType ) {
            case 'container':
                newWidget.elements = getUniqueId( elementCode.elements );
                container = elementor.getPreviewContainer();
                break;
            case 'section':
                newWidget.elements = getUniqueId( elementCode.elements );
                container = elementor.getPreviewContainer();
                break;
            case 'column':
                newWidget.elements = getUniqueId( elementCode.elements );
                switch( getElementType ){
                    case 'widget':
                        container = element.getContainer().parent.parent;
                        break;
                    case 'column':
                        container = element.getContainer().parent;
                        break;
                    case 'section':
                        container = element.getContainer();
                        break;
                }
                break;
            case 'widget':
                newWidget.widgetType = newElement.elementType;
                container = element.getContainer();
                switch( getElementType ) {
                    case 'widget':
                        container = element.getContainer().parent;
                        getElementType.index = element.getOption( "_index" ) + 1;
                        break;
                    case 'column':
                        container = element.getContainer();
                        break;
                    case 'section':
                        container = element.children.findByIndex(0).getContainer();
                        break;
                }
                break;
        }

        importContent( newWidget, elementCode, container );
    }

    var HTMegaManageData = {
        copy : function ( element, menutypekey ) {
            var copiedData = {};
            copiedData.elementType = menutypekey == "widget" ? element.model.get( "widgetType" ) : null;
            copiedData.elementCode = element.model.toJSON();
            xdLocalStorage.setItem( 'htmega-cp-element', JSON.stringify(copiedData), function (data) {
                elementor.notifications.showToast({
                    message: elementor.translate('Element Copied!')
                });
            });
        },
        paste : function ( element ) {
            xdLocalStorage.getItem( 'htmega-cp-element', function ( newElement ) {
                processImport( JSON.parse( newElement.value ), element );
                elementor.notifications.showToast({
                    message: elementor.translate('Element Pasted!')
                });
            });
        }
    };

    function prepareMenuItem( groups, element, menutypekey ) {
        var index = _.findIndex( groups, function ( element ) {
            return 'clipboard' === element.name;
        });

        groups.splice(index + 1, 0, {
            name: "htmega_" + menutypekey,
            actions: [
                {
                    name: 'htmega_copy',
                    title: htmegacrosscp.copy,
                    icon: 'eicon-clone',
                    callback: function () {
                        HTMegaManageData.copy( element, menutypekey )
                    }
                },
                {
                    name: 'htmega_paste',
                    title: htmegacrosscp.paste,
                    icon: 'eicon-copy',
                    callback: function () {
                        HTMegaManageData.paste( element ) 
                    }
                },
            ]
        });
        return groups;
    }

    elementor.hooks.addFilter('elements/widget/contextMenuGroups', function (groups, element) {
        return prepareMenuItem( groups, element, 'widget' );
    });

    elementor.hooks.addFilter('elements/section/contextMenuGroups', function (groups, element) {
        return prepareMenuItem( groups, element, 'section' );
    });

    elementor.hooks.addFilter('elements/column/contextMenuGroups', function (groups, element) {
        return prepareMenuItem( groups, element, 'column' );
    });
    elementor.hooks.addFilter('elements/container/contextMenuGroups', function (groups, element) {
        return prepareMenuItem( groups, element);
    });



} )( jQuery );