(function () {
    // TO TRIGGER TEH FILE UPLOADER WHEN CLICKING ON THE UPLOAD FILE SVG
    document.getElementById('svgFileUpload').addEventListener('click', function () {
        document.getElementById('fileupload').click();
    });

    document.getElementById('fileupload').addEventListener('change', function (event) {
        let files = event.target.files;

        for (let file of files) {
            let formData = new FormData();
            formData.append('file', file);
            formData.append('filename', file.name);

            // Display the file during upload
            if (file.type.startsWith('image/')) {
                displayImageDuringUpload(file);
            } else {
                displayDocumentDuringUpload(file);
            }

            // Perform the upload
            fetch(`${protocol}://${osinaDomain}/chat-file-uploader/`, {
                method: 'POST',
                body: formData,
            })
                .then(response => response.json())
                .then(data => {
                    if (data.data === 'Uploaded Successfully') {
                        const fullPath = `${protocol}://${osinaDomain}/${data.existingPath}`;
                        updateSelectTag(fullPath, file.name);
                        if (file.type.startsWith('image/')) {
                            osichatSocket.send(JSON.stringify({ 'event_type': 'uploaded_file', 'path': data.existingPath, 'file_type': 'image', 'file_name': file.name }));
                        } else {
                            osichatSocket.send(JSON.stringify({ 'event_type': 'uploaded_file', 'path': data.existingPath, 'file_type': 'document', 'file_name': file.name }));
                        }
                    } else {
                        console.error('Upload failed');
                    }
                })
                .catch(error => console.error('Error:', error));
        }
        event.target.value = '';
    });

    function displayImageDuringUpload(file) {
        let reader = new FileReader();
        reader.onload = function (event) {
            let mainDiv = document.createElement('div');
            mainDiv.className = 'w-full flex items-end justify-end gap-2'
            let outerDiv = document.createElement('div');
            outerDiv.id = 'uploading-' + file.name;
            outerDiv.className = 'max-w-[80%] p-4 rounded-l-3xl rounded-tr-3xl text-white shadow-md text-sm leading-6 bg-opacity-70 bg-osiblue';

            let div = document.createElement('div');
            let img = document.createElement('img');
            img.src = event.target.result;
            img.style.opacity = '0.2';

            div.appendChild(img);

            outerDiv.appendChild(div);

            mainDiv.appendChild(outerDiv);

            document.getElementById('messages').appendChild(mainDiv);
            scrollBottom();
        };
        reader.readAsDataURL(file);
    }


    function displayDocumentDuringUpload(file) {
        let mainDiv = document.createElement('div');
        mainDiv.className = 'w-full flex items-end justify-end gap-2'
        let outerDiv = document.createElement('div');
        outerDiv.id = 'uploading-' + file.name;
        outerDiv.className = 'max-w-[80%] p-4 rounded-l-3xl rounded-tr-3xl text-white shadow-md text-sm leading-6 bg-opacity-70 bg-osiblue';

        let flexContainer = document.createElement('div');
        flexContainer.className = 'w-full flex items-center gap-1';

        let svg = `
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-7 text-white notFilledSvg">
            <path d="M8 7L16 7" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
            <path d="M8 11L12 11" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
            <path d="M13 21.5V21C13 18.1716 13 16.7574 13.8787 15.8787C14.7574 15 16.1716 15 19 15H19.5M20 13.3431V10C20 6.22876 20 4.34315 18.8284 3.17157C17.6569 2 15.7712 2 12 2C8.22877 2 6.34315 2 5.17157 3.17157C4 4.34314 4 6.22876 4 10L4 14.5442C4 17.7892 4 19.4117 4.88607 20.5107C5.06508 20.7327 5.26731 20.9349 5.48933 21.1139C6.58831 22 8.21082 22 11.4558 22C12.1614 22 12.5141 22 12.8372 21.886C12.9044 21.8623 12.9702 21.835 13.0345 21.8043C13.3436 21.6564 13.593 21.407 14.0919 20.9081L18.8284 16.1716C19.4065 15.5935 19.6955 15.3045 19.8478 14.9369C20 14.5694 20 14.1606 20 13.3431Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
        </svg>
    `;

        let svgDiv = document.createElement('div');
        svgDiv.innerHTML = svg;

        let textContainer = document.createElement('div');
        textContainer.className = 'flex flex-col';

        let uploadingText = document.createElement('span');
        uploadingText.id = 'uploading-' + file.name;
        uploadingText.textContent = 'Uploading...';

        let fileNameDiv = document.createElement('div');
        fileNameDiv.className = 'file-name';
        fileNameDiv.textContent = file.name;

        textContainer.appendChild(uploadingText);
        textContainer.appendChild(fileNameDiv);

        flexContainer.appendChild(svgDiv);
        flexContainer.appendChild(textContainer);

        outerDiv.appendChild(flexContainer);

        mainDiv.appendChild(outerDiv);

        document.getElementById('messages').appendChild(mainDiv);

        scrollBottom();
    }




    function updateSelectTag(path, fileName) {
        let option = document.createElement('option');
        option.value = path;
        option.textContent = fileName;
        option.selected = true;
        document.getElementById('filePathInput').appendChild(option);
    }

})();
