<?php
/**
 * @category Magentech
 * @package Sm_AttributesSearch
 * @version 2.0.0
 * @copyright Copyright (c) 2018 YouTech Company. All Rights Reserved.
 * @license - Copyrighted Commercial Software
 * @author YouTech Company <contact@ytcvn.com>
 * @link http://www.magentech.com
 */

$_htmlId = $block->getHtmlId() ? $block->getHtmlId() : '_' . uniqid();
$_colspan = $block->isAddAfter() ? 2 : 1;
?>

<div class="design_theme_ua_regexp" id="grid<?php /* @escapeNotVerified */ echo $_htmlId ?>">
    <div class="admin__control-table-wrapper">
        <table class="admin__control-table" id="<?php /* @escapeNotVerified */ echo $block->getElement()->getId() ?>">
            <thead>
            <tr>
                <?php foreach ($block->getColumns() as $columnName => $column) :
                    if ($columnName == 'order_attr') { ?>
                        <th class="col-draggable" ></th>
                    <?php } else { ?>
                        <th><?php /* @escapeNotVerified */ echo $column['label'] ?></th>
                    <?php } ?>  
                <?php endforeach;?>
                <th class="col-actions" colspan="<?php /* @escapeNotVerified */ echo $_colspan ?>">
                    <?php /* @escapeNotVerified */ echo __('Action') ?>
                </th>
            </tr>
            </thead>
            <tfoot>
            <tr>
                <td colspan="<?php echo count($block->getColumns())+$_colspan ?>" class="col-actions-add">
                    <button id="addToEndBtn<?php /* @escapeNotVerified */ echo $_htmlId ?>" 
                    class="action-add" title="<?php /* @escapeNotVerified */ echo __('Add') ?>" type="button">
                        <span><?php /* @escapeNotVerified */ echo $block->getAddButtonLabel() ?></span>
                    </button>
                </td>
            </tr>
            </tfoot>
            <tbody id="addRow<?php /* @escapeNotVerified */ echo $_htmlId ?>" data-role="options-container"></tbody>
        </table>
    </div>
    <input type="hidden" name="<?php /* @escapeNotVerified */ echo $block->getElement()->getName() ?>[__empty]"
           value="" />

    <script>
        require([
            'mage/template',
            'prototype'
        ], function (mageTemplate) {
        // create row creator
        window.arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?> = {

            // define row prototypeJS template
            template: mageTemplate(
                '<tr id="<%- _id %>">'
                    <?php foreach ($block->getColumns() as $columnName => $column) : ?>
                    <?php if ($columnName == 'order_attr') { ?>
                    +'<td class="col-draggable" style="vertical-align:middle">'
                    +'<div data-role="draggable-handle" class="draggable-handle" title="Sort Option">'
                    + '<?php /* @escapeNotVerified */ echo $block->renderCellTemplate($columnName) ?>'
                    +'<\/div>'
                    +'<\/td>'
                    <?php } else { ?>
                    + '<td>'
                    + '<?php /* @escapeNotVerified */ echo $block->renderCellTemplate($columnName) ?>'
                    + '<\/td>'
                    <?php } ?>      
                    <?php endforeach; ?>

                    <?php if ($block->isAddAfter()) : ?>
                    + '<td><button class="action-add" type="button" id="addAfterBtn<%- _id %>">'
                    +'<span><?php /* @escapeNotVerified */ echo __('Add after') ?><\/span><\/button>'
                    +'<\/td>'
                    <?php endif; ?>

                    + '<td class="col-actions">'
                    +'<button onclick="arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?>.del(\'<%- _id %>\')" '
                    +'class="action-delete" type="button"><span><?php /* @escapeNotVerified */ echo __('Delete'); ?>'
                    +'<\/span><\/button><\/td>'
                +'<\/tr>'
            ),

            add: function(rowData, insertAfterId) {
                // generate default template data
                var templateValues;

                // Prepare template values
                if (rowData) {
                    templateValues = rowData;
                } else {
                    var d = new Date();
                    templateValues = {
                <?php foreach ($block->getColumns() as $columnName => $column) : ?>
                    <?php  /* @escapeNotVerified */ echo $columnName; ?>: '', 'option_extra_attrs': {},
                <?php endforeach; ?>
                        _id: '_' + d.getTime() + '_' + d.getMilliseconds(),
                        order_attr: $$('input[data-role="order"]').length + 1
                };
            }

            // Insert new row after specified row or at the bottom
            if (insertAfterId) {
            Element.insert($(insertAfterId), {after: this.template(templateValues)});
        } else {
            Element.insert($('addRow<?php /* @escapeNotVerified */ echo $_htmlId ?>'), 
            {bottom: this.template(templateValues)});
        }

        // Fill controls with data
        if (rowData) {
            var rowInputElementNames = Object.keys(rowData.column_values);
            for (var i = 0; i < rowInputElementNames.length; i++) {
                if ($(rowInputElementNames[i])) {
                    $(rowInputElementNames[i]).setValue(rowData.column_values[rowInputElementNames[i]]);
                }
            }
        }

            // Add event for {addAfterBtn} button
            <?php if ($block->isAddAfter()) : ?>
            Event.observe('addAfterBtn' + templateValues._id, 'click', this.add.bind(this, false, templateValues._id));
            <?php endif; ?>
            },

            del: function(rowId) {
                $(rowId).remove();
            }
        }

        // bind add action to "Add" button in last row
        Event.observe('addToEndBtn<?php /* @escapeNotVerified */ echo $_htmlId ?>', 
            'click', 
            arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?>.add.bind(
            arrayRow<?php /* @escapeNotVerified */ echo $_htmlId ?>,
            false, false));

        // add existing rows
        <?php
        foreach ($block->getArrayRows() as $_rowId => $_row) {
            /* @escapeNotVerified */ echo "arrayRow{$_htmlId}.add(" . $_row->toJson() . ");\n";
        }
        ?>

        // Toggle the grid availability, if element is disabled (depending on scope)
        <?php if ($block->getElement()->getDisabled()) :?>
            toggleValueElements({checked: true}, $('grid<?php /* @escapeNotVerified */ echo $_htmlId ?>').parentNode);
        <?php endif;?>
        });
    </script>
    <script type="text/javascript">
     require([
            'jquery',
            'jquery/ui'
        ], function ($, sortable) {
             $('[data-role=options-container]').sortable({
                distance: 8,
                tolerance: 'pointer',
                cancel: 'input, button, select',
                axis: 'y',
                update: function () {
                    $('[data-role=options-container] [data-role=order]').each(function (index, element) {
                        $(element).val(index + 1);
                    });
                }
            });
        });
    </script>
</div>
