<html class="bx-core bx-win bx-no-touch bx-no-retina bx-chrome">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="description" content="Сравнение документов">
        <title>Слово VS Слово - инструмент для сравнения текстов и таблиц</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="{{ url_for('static', filename='css/diff2html/github.min.css') }}" />
        <link rel="stylesheet" href="{{ url_for('static', filename='css/diff2html/diff2html.min.css') }}" />
        <link rel="stylesheet" href="{{ url_for('static', filename='css/main/main.css') }}" />
        <script type="text/javascript" src="{{ url_for('static', filename='js/diff2html/diff2html-ui.min.js') }}"></script>
        <script type="text/javascript" src="{{ url_for('static', filename='js/main/main.js') }}"></script>
    </head>
    <body>
        <div class="home-banner">
            <div class="home-banner-content">
                <h1 class="gradient">Слово VS Слово</h1>
                <p>Сравнение документов</p>
                <form form method="post" class="compare" enctype="multipart/form-data">
                    <div class="compare-files">
                        <div class="file-drop-area first-file-drop-area">
                            <span class="fake-btn">Выберите файл</span>
                            <div class="item-delete"></div>
                            <span class="file-msg">или перетащите его сюда</span>
                            <input class="file-input" name="original" enctype="multipart/form-data" type="file" required="" accept=".doc,.docx,.odt,.js,.py,.css,.php,.go,.txt,.html,.tsx,.jsx,.json,.sh,.log,.conf,.pdf">
                            <div class="file-drop-area-errors"></div>
                        </div>
                        <div class="file-drop-area second-file-drop-area">
                            <span class="fake-btn">Выберите файл</span>
                            <div class="item-delete"></div>
                            <span class="file-msg">или перетащите его сюда</span>
                            <input class="file-input" name="compare" enctype="multipart/form-data" type="file" required="" accept=".doc,.docx,.odt,.js,.py,.css,.php,.go,.txt,.html,.tsx,.jsx,.json,.sh,.log,.conf,.pdf" multiple>
                            <div class="file-drop-area-errors"></div>
                        </div>
                    </div>
                    <button class="button" type="submit">Сравнить</button>
                </form>
            </div>
        </div>
        <div class="compare-result">
            <div class="container">
            </div>
        </div>
    </body>
    <script>
    $(document).ready(function() {

 





        function makeCustomFileInput(droparea) {
        const $droparea = $(droparea);
        const $fileInput = $droparea.find('.file-input');
        const $delete = $droparea.find('.item-delete');
        const $message = $droparea.find('.file-msg');
        const $errors = $droparea.find('.file-drop-area-errors');

        $fileInput.on('change', function() {
            $errors.hide();
            let filesCount = $(this)[0].files.length;
            let $textContainer = $(this).prev();
            let allowedFiles = $(this).attr('accept').split(',');

            for (var i = 0; i < allowedFiles.length; i++) {
                allowedFiles[i] = allowedFiles[i].replace('.', '');
            }

            if (filesCount === 1) {
                let fileName = $(this).val().split('\\').pop();
                let fileExt = fileName.split('.').pop();
                var sliced = fileName.slice(0, 20);
                if (sliced.length < fileName.length) {
                    sliced += '...';
                }

                if (allowedFiles.includes(fileExt)) {
                    $textContainer.text(sliced);
                    $delete.css('display', 'inline-block');
                    $droparea.addClass('is-active');
                } else {
                    $errors.html('Формат файла не поддерживается! Допустимые форматы: ' + $(this).attr('accept'));
                    $errors.show();
                    $errors.animate({
                        opacity: 1
                    }, 500);
                }
                
            } else if (filesCount === 0) {
                $textContainer.text('или перетащите его сюда');
                $delete.css('display', 'none');
                $droparea.removeClass('is-active');
            } else {
                $textContainer.text(filesCount + ' файлов выбрано');
                $delete.css('display', 'inline-block');
                $droparea.addClass('is-active');

            }
        });

        $delete.on('click', function() {
            $fileInput.val(null);
            $message.text('или перетащите его сюда');
            $delete.css('display', 'none');
            $droparea.removeClass('is-active');
            $errors.hide();
        });
    }

    makeCustomFileInput('.first-file-drop-area');
    makeCustomFileInput('.second-file-drop-area');

    $('.compare').submit(function(e) {
        e.preventDefault();
        var button = $(this).find('.button');
        button.css('opacity', 0.3);
        let checkext=false;
        Array.from($('input[name="compare"]')[0].files).forEach(function(elem) {
            if ($('input[name="original"]')[0].files[0].name.split('.').pop() != elem.name.split('.').pop()){
            checkext=true;};
        });
        if (checkext){
            alert("Сравнение файлов с разными расширениями невозможно")
        } else {
                $.ajax({
                    url: window.location.origin,
                    type: 'POST',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,

                    success: function(data) {
                        button.css('opacity', 1);
                        $('.compare-result .container').html('<div id="myDiffElement"></div>');
                        $('.compare-result .container').prepend('<div class="compare-result-title"><h2>Результат</h2> <div class="reset-compare">Сбросить</div><div>');
                        var targetElement = document.getElementById('myDiffElement');
                        var configuration = {
                            drawFileList: true,
                            fileListToggle: true,
                            fileListStartVisible: true,
                            fileContentToggle: true,
                            matching: 'lines',
                            diffStyle: 'word',
                            matchWordsThreshold: 0.25,
                            matchingMaxComparisons:100000,
                            maxLineSizeInBlockForComparison:10000,
                            outputFormat: 'side-by-side',
                            synchronisedScroll: true,
                            highlight: true,
                            renderNothingWhenEmpty: false,
                        };
                        var diff2htmlUi = new Diff2HtmlUI(targetElement,data, configuration);

                        $('.compare-result').addClass('compared');
                        $('.home-banner h1').animate({
                            "font-size": "0px",
                            "opacity": 0,
                            "line-height": "0px",
                        }, 400);
                        $('.home-banner').animate({
                            height: "300px",
                            "padding-top": "50px",
                            "padding-bottom": "30px",
                        }, 600);
                        diff2htmlUi.draw();
                        diff2htmlUi.highlightCode();


                        numbers = document.querySelectorAll( '.d2h-code-side-linenumber' );
                        numbers.forEach(function(number) {
                            number.addEventListener('click', function(event) {
                                var xpath = "//td[contains(@class,'d2h-code-side-linenumber') and normalize-space(text()) = '"+event.target.innerText+"']";
                                const result = document.evaluate(
                                    xpath,
                                    document,
                                    null,
                                    XPathResult.ANY_TYPE,
                                    null,
                                );
                                let nodes = [];
                                while ((node = result.iterateNext())) {
                                    if (node.closest('.d2h-file-wrapper').id==event.target.closest('.d2h-file-wrapper').id){
                                    nodes.push(node);
                                    }
                                }
                                nodes[1].closest('.d2h-code-wrapper').style.top = nodes[0].offsetTop - nodes[1].offsetTop;
                            });
                        });

                   

                        
                    }
                });
        }
    });

    $('.compare-result').on('click', '.reset-compare', function() {
        $('.compare-result .container').html('');
        $('.compare-result').removeClass('compared');
        $('.home-banner h1').animate({
            "font-size": "110px",
            "opacity": 1,
            "line-height": "110px",
        }, 400);
        $('.home-banner').animate({
            height: "100vh",
            "padding-top": "0",
            "padding-bottom": "0",
        }, 600);
    })


});
    </script>
</html>

