import('bootstrap');
import $ from 'jquery';
import 'datatables.net-bs5';
import {initContactSelect2} from './contactSelect2';

require('jquery-circle-progress');

$(function () {
    if ($('#example').length) {
        $('#example').DataTable();
    }
});

$(function () {
    if (!$('#shared_file_contact').length) {
        initContactSelect2();
    }

    if ($('#circle').length) {
        // @ts-ignore
        var c4 = $('#circle').circleProgress({
            value: 0,
            size: 100,
            animation: false,
            fill: {
                gradient: ['blue', 'cyan'],
            },
        });

        $('#fileUpload').on('change', function () {
            // @ts-ignore
            var file = (this as HTMLInputElement).files[0];
            var formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: 'YOUR_UPLOAD_ENDPOINT',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function () {
                    var xhr = new window.XMLHttpRequest();

                    xhr.upload.addEventListener(
                        'progress',
                        function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                console.log(percentComplete.toFixed(2));

                                setTimeout(function () {
                                    c4.circleProgress('value', percentComplete);
                                }, 1000);

                                $(c4)
                                    .find('strong')
                                    .html(
                                        Math.round(percentComplete * 100) +
                                        '<i>%</i>'
                                    );
                            }
                        },
                        false
                    );

                    return xhr;
                },
                success: function (data) {
                    console.log('File has been uploaded successfully');
                },
                error: function (err) {
                    console.error('Error during the file upload:', err);
                },
            });
        });
    }
});
