@if($edit)
    <div class="mceNonEditable component-container" data-component-key="htmlWrapper">
<a href="#" class="btn btn-danger pull-right delete-component">X</a>
        <h4>@lang('hilco::app.html_wrapper')</h4>
        <p>@lang('hilco::app.renders_text_html_based_on_customer')</p>
        <div class="view-full-container">
            @include('hilco::components.targetCustomer.viewSelector', ['alternateViews' => $alternateViews ?? []])
            @include('hilco::components.htmlWrapperView',
            [
                'viewId' => 0,
                'html' => $html,
                'defaultVisibility' => $defaultVisibility ?? 'Visible',
                'visibleDates' => $visibleDates ?? [],
                'visibleDatesFormatted' => $visibleDatesFormatted ?? 'All',
                'default' => true
            ])
            @foreach($alternateViews ?? [] as $altViewId => $altView)
                @include('hilco::components.htmlWrapperView',
                [
                    'viewId' => $altViewId,
                    'html' => Arr::get($altView, 'html', ''),
                    'targetCustomers' => Arr::get($altView, 'targetCustomers', []),
                    'targetCustomersFormatted' => Arr::get($altView, 'targetCustomersFormatted', 'None'),
                    'visibleDates' => Arr::get($altView, 'visibleDates', []),
                    'visibleDatesFormatted' => Arr::get($altView, 'visibleDatesFormatted', 'None'),
                    'default' => false
                ])
            @endforeach
        </div>
    </div>
@endif

@if($script)
    <script type="text/javascript">
        registerComponent('htmlWrapper', {
            menuText: '@lang('hilco::app.html_wrapper')',
            bladeTemplate: 'hilco::components.htmlWrapper',
            init: function (body) {
                initViewFunctions(body);
                $(body).on('click', '.htmlwrapper-html', function () {
                    var button = $(this);
                    var htmlEditor = new $.fn.dataTable.Editor({
                        title: 'Text/HTML',
                        fields: [
                            {
                                label: 'Text/HTML',
                                name: 'html',
                                type: 'textarea',
                                def: $(button).attr('data-html'),
                            },
                        ]
                    }).title('@lang('hilco::app.html_wrapper')').buttons({
                        label: "@lang('hilco::app.save')",
                        fn: function () {
                            this.submit(null, null, function (data) {
                                $(button).attr('data-html', data.data.key.html);
                                $(button).text('data-html', data.data.key.html);
                            });
                        }
                    }).on('open', function (event, displayMode, action) {
                        // displayMode can be 'main' 'inline' or 'bubble'
                        if (displayMode === "main") {
                            // action can be 'create' 'edit' or 'remove'
                            if (action === "create" || action === "edit") {
                                let rawHtml = htmlEditor.get("html");
                                let formattedHtml = formatHtml(rawHtml);
                                htmlEditor.set("html", formattedHtml);
                            }
                        }
                    }).on('preSubmit', function (event, data, action) {
                        $.each(data.data, function (key, values) {
                            data.data[key]["html"] = unformatHtml(data.data[key]["html"]);
                        });
                    });
                    htmlEditor.edit('key');
                });
            },
            serialize: function (componentNode) {
                var viewDiv = $(componentNode).find('div.view-container.default');
                var alternateViews = {};
                viewDiv.closest('.view-full-container').find('.view-container.alternate').each(function () {
                    var targetCustomers = {};
                    try{
                        targetCustomers = JSON.parse($(this).attr('data-target-customers'));
                    }catch (e){
                        //use the empty object
                    }
                    var visibleDates = {};
                    try{
                        visibleDates = JSON.parse($(this).attr('data-visible-dates'));
                    }catch (e){
                        //use the empty object
                    }
                    alternateViews[$(this).attr('data-view-id')] = {
                        html: $(this).find('a.htmlwrapper-html').data('html'),
                        targetCustomers: targetCustomers,
                        targetCustomersFormatted: $(this).find('.view-targetcustomers').text(),
                        visibleDates: visibleDates,
                        visibleDatesFormatted: $(this).find('.view-visibledates').text(),
                    }
                });
                var visibleDates = {};
                try{
                    visibleDates = JSON.parse(viewDiv.attr('data-visible-dates'));
                }catch (e){
                    //use the empty object
                }
                var result = {
                    html: viewDiv.find('a.htmlwrapper-html').data('html'),
                    defaultVisibility: viewDiv.attr('data-default-visibility').trim(),
                    visibleDates: visibleDates,
                    visibleDatesFormatted: viewDiv.find('.view-visibledates').text(),
                    alternateViews: alternateViews
                };

                return result;
            },
        });

        /**
         * This doesn't appear to actually do indenting, but it does newlines at least
         * @param htmlText
         * @returns {string}
         */
        function formatHtml (htmlText) {
            if (htmlText === undefined || htmlText === "") {
                return "";
            }
            let tab = "    "; // "\t" doesn't work either, nor does using &nbsp; or &emsp;
            let result = "";
            let indent = "";

            htmlText.trim().split(/>\s*</).forEach(function (element, index) {
                if (element.match(/^\/\w/)) {
                    indent = indent.substring(tab.length);
                }
                if (index == 0) {
                    if (element.endsWith(">")) result += element;
                    else result += element + '>\n';
                } else {
                    if (element.endsWith(">")) result += indent + "<" + element;
                    else result += indent + '<' + element + '>\n';
                }
                if (element.match(/^(<)?\w[^>]*[^\/]$/) && !element.startsWith("input")) {
                    indent += tab;
                }
            });

            return result;//.substring(1, result.length-3);
        }

        /**
         * "de-format" the HTML from formatHTML before saving in the database
         * @param htmlText
         * @returns {string}
         */
        function unformatHtml (htmlText) {
            let result = "";
            htmlText.split(/\n/).forEach(function (element) {
                result += element;
            });
            return result;
        }
    </script>
@endif

@if($view)
    @include('hilco::components.targetCustomer.viewRenderer', ['blade' => 'hilco::components.htmlWrapperView', 'bladeViewArgs' => ['html' => $html, 'defaultVisibility' => $defaultVisibility ?? 'Visible', 'alternateViews' => $alternateViews?? []], 'mode' => 'view'])
@endif
