<?php

defined('JPATH_BASE') or die();

jimport('joomla.form.formfield');

class JFormFieldImport extends JFormField
{
	var $type = 'import';

	function getInput() {
        ob_start();
        $root = dirname(dirname((JURI::current())));
        $action = $root . '/plugins/content/themlerexportimport/core/index.php?action=import';
        ?>
        <style type="text/css">
            #file-list {
                list-style-type: none;
                margin: 0;
                padding: 0;
            }
            #file-list li {
                margin: 10px;
                width: 152px;
                text-align: center;
                display: inline-block;
            }

            #file-list div.progress {
                width: 150px;
                border: 1px solid #888888;
                height: 18px;
                text-align: center;
                background-image: url('<?php echo $root; ?>/plugins/content/themlerexportimport/fields/pbar_bgr.png');
                background-repeat: no-repeat;
                background-position: -150px center;
            }

            #log {
                color: blue;
            }

        </style>
        <input type="file" name="file" id="file-field" multiple="true" />
        <button id="upload-all" disabled class="btn"><?php echo JText::_('PLG_CONTENT_THEMLEREXPORTIMPORT_IMPORTBUTTON_TEXT'); ?></button>
        <ul id="file-list"></ul>
        <div id="log"></div>
        <script>
            jQuery(function($) {

                var fileInput = $('#file-field');
                var fileList = $('ul#file-list');
                var uploadBtn = $("#upload-all");
                var replaceChbx = $('input[id*="replacecontent"]');
                var previousContentData = $('input[id*="idsData"]');

                var replaceStatus = replaceChbx[0].checked ? 'yes' : 'no';

                replaceChbx.click(function() {
                    replaceStatus = this.checked ? 'yes' : 'no';
                });

                function log(msg, color) {
                    $('#log').append($('<div></div>').text(msg).css('color', color));
                    setTimeout(function(){
                        $('#log').html('');
                    }, 2000)
                }

                function ChunkedUploader(file, params) {
                    var _file = file;
                    if (_file instanceof Uint8Array) {
                        _file = new Blob([_file]);
                    }
                    var CHUNK_SIZE = 1024 * 1024; // 1 Mb
                    var uploadedChunkNumber = 0, allChunks;
                    var fileName = (_file.name || window.createGuid()).replace(/[^A-Za-z0-9\._]/g, '');
                    var fileSize = _file.size || _file.length;
                    var total = Math.ceil(fileSize / CHUNK_SIZE);

                    var rangeStart = 0;
                    var rangeEnd = CHUNK_SIZE;
                    validateRange();

                    var sliceMethod;

                    if ('mozSlice' in _file) {
                        sliceMethod = 'mozSlice';
                    }
                    else if ('webkitSlice' in _file) {
                        sliceMethod = 'webkitSlice';
                    }
                    else {
                        sliceMethod = 'slice';
                    }

                    this.upload = upload;

                    function upload() {
                        var data;

                        setTimeout(function () {
                            var requests = [];

                            for (var chunk = 0; chunk < total - 1; chunk++) {
                                data = _file[sliceMethod](rangeStart, rangeEnd);
                                requests.push(createChunk(data));
                                incrementRange();
                            }

                            allChunks = requests.length;

                            $.when.apply($, requests).then(
                                function success() {
                                    var lastChunkData = _file[sliceMethod](rangeStart, rangeEnd);

                                    createChunk(lastChunkData, {last: true})
                                        .done(onUploadCompleted)
                                        .fail(onUploadFailed);
                                },
                                onUploadFailed
                            );
                        }, 0);
                    }

                    function createChunk(data, params) {
                        var formData = new FormData();
                        formData.append('filename', fileName);
                        formData.append('replaceStatus', replaceStatus);
                        formData.append('chunk', new Blob([data], { type: 'application/octet-stream' }), 'blob');

                        if (typeof params === 'object') {
                            for (var i in params) {
                                if (params.hasOwnProperty(i)) {
                                    formData.append(i, params[i]);
                                }
                            }
                        }

                        return $.ajax({
                            url: '<?php echo $action; ?>',
                            data: formData,
                            type: 'POST',
                            mimeType: 'application/octet-stream',
                            processData: false,
                            contentType: false,
                            headers: (rangeEnd <= fileSize) ? {
                                'Content-Range': ('bytes ' + rangeStart + '-' + rangeEnd + '/' + fileSize)
                            } : {},
                            success: onChunkCompleted,
                            error: function (xhr, status) {
                                alert('Failed  chunk');
                            }
                        });
                    }

                    function validateRange() {
                        if (rangeEnd > fileSize) {
                            rangeEnd = fileSize;
                        }
                    }

                    function incrementRange() {
                        rangeStart = rangeEnd;
                        rangeEnd = rangeStart + CHUNK_SIZE;
                        validateRange();
                    }

                    function onUploadCompleted(response, status, xhr) {
                        previousContentData.val(response);
                        params.complete();
                    }

                    function onUploadFailed(xhr, status) {
                        alert('onUploadFailed');
                    }

                    function onChunkCompleted() {

                        if (uploadedChunkNumber >= allChunks)
                            return;

                        ++uploadedChunkNumber;
                        params.progress(Math.round((100 * uploadedChunkNumber)/allChunks));
                    }
                }

                function updateProgress(bar, value) {
                    var width = bar.width();
                    var bgrValue = -width + (value * (width / 100));
                    bar.attr('rel', value).css('background-position', bgrValue+'px center').text(value+'%');
                }

                function displayFiles(files) {
                    var imageType = /(zip).*/;
                    var num = 0;

                    $.each(files, function(i, file) {

                        if (!file.type.match(imageType)) {
                            alert('File is not allowed: `'+file.name+'` (type '+file.type+')');
                            fileInput.val('');
                            fileList.html('');
                            uploadBtn.attr('disabled', true);
                            return true;
                        }
                        num++;
                        var li = $('<li/>');
                        var img = $('<img/>').appendTo(li);
                        $('<div/>').addClass('progress').attr('rel', '0').text('0%').appendTo(li);
                        li.get(0).file = file;
                        fileList.html(li);
                        var thumbDataUrl = "data:image/png;base64, ";
                        img.attr('src', thumbDataUrl);
                        img.attr('width', 150);
                        uploadBtn.attr('disabled', false);
                    });
                }

                fileInput.bind({
                    change: function() {
                        displayFiles(this.files);
                    }
                });

                uploadBtn.click(function(e) {
                    e.preventDefault();
                    fileList.find('li').each(function() {

                        var uploadItem = this;
                        var pBar = $(uploadItem).find('.progress');
                        var onprogress = function(percents) {
                                updateProgress(pBar, percents);
                            },
                            oncomplete = function() {
                                updateProgress(pBar, 100);
                                setTimeout(function(){
                                    fileInput.val('');
                                    fileList.html('');
                                    uploadBtn.attr('disabled', true);
                                    log('The sample data has bees successfully installed.');
                                }, 2000);

                            };

                        var uploader = new ChunkedUploader(uploadItem.file, {'progress' : onprogress, 'complete' : oncomplete});

                        uploader.upload();
                    });
                });
            });
        </script>
        <?php

        return ob_get_clean();

	}
}