<?php
/**
 * Copyright © 2016 maijindou.com All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var $block \Magento\Swatches\Block\Adminhtml\Attribute\Edit\Options\Visual */
?>
<fieldset class="fieldset">
    <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Manage Swatch (values of your attribute)') ?></span></legend>
    <div id="swatch-visual-options-panel">
        <?php //@todo move style to css file ?>
        <table class="data-table" style="clear: both;" cellspacing="0">
            <thead>
            <tr id="swatch-visual-options-table">
                <th class="col-draggable"></th>
                <th class="col-default"><?php /* @escapeNotVerified */ echo __('Is Default') ?></th>
                <th><?php /* @escapeNotVerified */ echo __('Swatch') ?></th>
                <?php
                $storelist = $block->getStores();
                foreach ($storelist as $_store):
                    ?>
                    <th><?php /* @escapeNotVerified */ echo $_store->getName() ?></th>
                <?php endforeach;
                $storetotal = count($storelist) + 3;
                ?>
                <th class="col-delete">&nbsp;</th>
            </tr>
            </thead>
            <tbody data-role="swatch-visual-options-container" class="ignore-validate"></tbody>
            <tfoot>
            <tr>
                <th colspan="<?php /* @escapeNotVerified */ echo $storetotal; ?>">
                    <input type="hidden" class="required-visual-swatch-entry" name="visual_swatch_validation"/>
                </th>
            </tr>
            <tr>
                <th colspan="<?php /* @escapeNotVerified */ echo $storetotal; ?>" class="col-actions-add">
                    <?php if (!$block->getReadOnly() && !$block->canManageOptionDefaultOnly()):?>
                        <button id="add_new_swatch_visual_option_button" title="<?php /* @escapeNotVerified */ echo __('Add Swatch'); ?>"
                                type="button" class="action- scalable add">
                            <span><?php /* @escapeNotVerified */ echo __('Add Swatch'); ?></span>
                        </button>
                    <?php endif; ?>
                </th>
            </tr>
            </tfoot>
        </table>
        <input type="hidden" id="swatch-visual-option-count-check" value="" />
    </div>
    <script id="swatch-visual-row-template" type="text/x-magento-template">
        <tr>
            <td class="col-draggable">
                <?php if (!$block->getReadOnly() && !$block->canManageOptionDefaultOnly()): ?>
                    <div data-role="draggable-handle" class="draggable-handle" title="<?php /* @escapeNotVerified */ echo __('Sort Option'); ?>"></div>
                <?php endif; ?>
                <input data-role="order" type="hidden" name="optionvisual[order][<%- data.id %>]"  value="<%- data.sort_order %>" <?php if ($block->getReadOnly() || $block->canManageOptionDefaultOnly()): ?> disabled="disabled"<?php endif; ?>/>
            </td>
            <td class="col-default">
                <input class="input-radio" type="<%- data.intype %>" name="defaultvisual[]" value="<%- data.id %>" <%- data.checked %><?php if ($block->getReadOnly()):?>disabled="disabled"<?php endif;?>/>
            </td>
            <td class="swatch-window-col-<%- data.id %> col-default <%- data.empty_class %>">
                <?php //@todo add logic getting swatch value from db */ ?>
                <input id="swatch_visual_value_<%- data.id %>" type="hidden" name="swatchvisual[value][<%- data.id %>]" value="<%- data.defaultswatch0 %>" />
                <div id="swatch_window_option_<%- data.id %>" style="border: 1px solid black; width: 30px; height: 30px; overflow: hidden; <%- data.swatch0 %>" onClick="this.next('div').toggle()"></div>

                <div id="swatch_container_option_<%- data.id %>" class="swatch_submenu_container" style="display: none;">
                    <div class="swatch_row" style="border:1px solid black; position: relative;">
                        <div class="swatch_row_name colorpicker_handler">
                            <p>Choose a color</p>
                        </div>
                    </div>
                    <div class="swatch_row" style="border:1px solid black;">
                        <form class="ignore-validate">
                            <input type="hidden" name="form_key" value="<?php /* @escapeNotVerified */ echo $block->getFormKey(); ?>" />
                            <input type="file" name="datafile" id="swatch_file_option_<%- data.id %>" onchange="fileUpload(this.previous('input'), this.form,'<?php /* @escapeNotVerified */ echo $block->getUrl('swatches/iframe/show'); ?>','swatch_window_option_<%- data.id %>'); return false;"><br />
                        </form>
                        <div class="swatch_row_name" onclick="$('swatch_file_option_<%- data.id %>').click();">
                            <p>Upload a file</p>
                        </div>
                    </div>
                    <div class="swatch_row" style="border:1px solid black;">
                        <div class="swatch_row_name" onclick="removeSwatch(this.up());">
                            <p>Clear</p>
                        </div>
                    </div>
                </div>
            </td>
            <?php foreach ($block->getStores() as $_store): ?>
                <td class="swatch-col-<%- data.id %>">
                    <input name="optionvisual[value][<%- data.id %>][<?php /* @escapeNotVerified */ echo $_store->getId() ?>]" value="<%- data.store<?php /* @escapeNotVerified */ echo $_store->getId() ?> %>" class="input-text<?php if ($_store->getId() == \Magento\Store\Model\Store::DEFAULT_STORE_ID): ?> required-option<?php endif; ?>" type="text" <?php if ($block->getReadOnly() || $block->canManageOptionDefaultOnly()):?> disabled="disabled"<?php endif;?>/>
                </td>
            <?php endforeach; ?>
            <td id="delete_button_swatch_container_<%- data.id %>" class="col-delete">
                <input type="hidden" class="delete-flag" name="optionvisual[delete][<%- data.id %>]" value="" />
                <?php if (!$block->getReadOnly() && !$block->canManageOptionDefaultOnly()):?>
                    <button title="<?php /* @escapeNotVerified */ echo __('Delete') ?>" type="button"
                            class="action- scalable delete delete-option"
                        >
                        <span><?php /* @escapeNotVerified */ echo __('Delete') ?></span>
                    </button>
                <?php endif;?>
            </td>
        </tr>
    </script>
    <script language="Javascript">
        function removeSwatch(element)
        {
            if(element.up().previous())
            {
                element.up().previous('input').value = '';
                element.up().previous().setStyle({'background': ''});
            }
            element.up().hide();
            element.up().previous().up().addClassName('unavailable');
        }

        function fileUpload(input, form, action_url, div_id)
        {
            if ($(div_id).firstDescendant()) {
                $(div_id).firstDescendant().remove();
            }
            var iframe = document.createElement("iframe");
            iframe.setAttribute("id", "upload_iframe");
            iframe.setAttribute("name", "upload_iframe");
            iframe.setAttribute("width", "0");
            iframe.setAttribute("height", "0");
            iframe.setAttribute("border", "0");
            iframe.setAttribute("style", "width: 0; height: 0; border: none;");
            form.parentNode.appendChild(iframe);
            window.frames['upload_iframe'].name = "upload_iframe";
            iframeId = document.getElementById("upload_iframe");
            var eventHandler = function () {
                if (iframeId.detachEvent)iframeId.detachEvent("onload", eventHandler); else iframeId.removeEventListener("load", eventHandler, false);
                if (iframeId.contentDocument) {
                    content = iframeId.contentDocument.body.innerHTML;
                } else if (iframeId.contentWindow) {
                    content = iframeId.contentWindow.document.body.innerHTML;
                } else if (iframeId.document) {
                    content = iframeId.document.body.innerHTML;
                    //hiddeninput.value = iframeId.document.body.innerHTML
                }
                var imageParams = JSON.parse(content);
                var fullMediaUrl = imageParams.swatch_path + imageParams.file_path;
                $(div_id).up().removeClassName("unavailable");
                $(div_id).previous('input').value = imageParams.file_path;
                document.getElementById(div_id).setStyle({'background': 'url(' + fullMediaUrl + ')', 'background-size': 'cover'});
                setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
            }
            if (iframeId.addEventListener)iframeId.addEventListener("load", eventHandler, true);
            if (iframeId.attachEvent)iframeId.attachEvent("onload", eventHandler);
            form.setAttribute("target", "upload_iframe");
            form.setAttribute("class", "ignore-validate");
            form.setAttribute("action", action_url);
            form.setAttribute("method", "post");
            form.setAttribute("enctype", "multipart/form-data");
            form.setAttribute("encoding", "multipart/form-data");
            form.submit();
            form.up().up().hide();
        }
    </script>
    <?php
    $values = [];
    foreach($block->getOptionValues() as $value) {
        array_push($values, $value->getData());
    }
    ?>
    <script type="text/x-magento-init">
        {
                "*": {
                    "Magento_Swatches/js/visual": {
                        "attributesData": <?php /* @escapeNotVerified */ echo json_encode($values); ?>,
                        "isSortable":  <?php echo (int)(!$block->getReadOnly() && !$block->canManageOptionDefaultOnly()) ?>,
                        "isReadOnly": <?php echo (int)$block->getReadOnly(); ?>
                    }
                }
            }
    </script>
</fieldset>
