<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ZIP Upload</title>
<link
	href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
	rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
	rel="stylesheet" />
</head>
<body>
	<div class="container">
		<h3 class="center-align">Setup Taric Database</h3>
		<div id="formSection" class="row">
			<form id="uploadForm" class="col s12" enctype="multipart/form-data">
				<div class="file-field input-field">
					<div class="btn blue-grey">
						<span>Select file</span> <input type="file" id="zipFile"
							name="file" accept=".zip" required>
					</div>
					<div class="file-path-wrapper">
						<input class="file-path validate" type="text"
							placeholder="Upload your ZIP file">
					</div>
				</div>
				<button class="btn waves-effect waves-light  blue-grey darken-3"
					type="submit" name="action">
					<i class="material-icons">cloud_upload</i> Upload
				</button>
			</form>
		</div>
		<div id="statusSection" class="row" style="display: none;">
			<div class="col s12">
				<h5 class="center-align" id="recordCount">Please wait</h5>
				<div class="progress">
					<div id="progressBar" class="indeterminate" style="width: 0%;"></div>
				</div>
				<p id="statusText" class="center-align">Initializing...</p>
			</div>
		</div>
	</div>


	<script
		src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
	<script>
	
	

		checkStatus();

	
        document.getElementById('uploadForm').addEventListener('submit', async function(event) {
            event.preventDefault();
            const formData = new FormData();
            const fileInput = document.getElementById('zipFile');

            if (fileInput.files.length === 0) {
                M.toast({html: 'Please select a file!'});
                return;
            }

            formData.append('file', fileInput.files[0]);

            try {
                const response = await fetch('/setup/upload', {
                    method: 'POST',
                    body: formData
                });             
                
                if (response.ok) {
                    document.getElementById('formSection').style.display = 'none';
                    document.getElementById('statusSection').style.display = 'block';
                    monitorStatus();
                } else {
                    const errorMessage = await response.text();
                    M.toast({html: errorMessage});
                }
            } catch (error) {
                console.error('Error uploading file:', error);
                M.toast({html: 'Error uploading file!'});
            }
        });
        
		async function checkStatus() {
			const response = await fetch('/setup/status');
			if (response.ok) {
				const status = await response.json();
				if (status.running) {
					document.getElementById('formSection').style.display = 'none';
					document.getElementById('statusSection').style.display = 'block';
					monitorStatus();
				}
			}
		}
        
        async function monitorStatus() {
        	var receivedRecords = false;
            const progressBar = document.getElementById('progressBar');
            const statusText = document.getElementById('statusText');
            const recordCount = document.getElementById('recordCount');

            const updateStatus = async () => {
                try {
                    const response = await fetch('/setup/status');
                    if (response.ok) {
                        const status = await response.json();
                        
                        if(receivedRecords == false && status.maxRecord != 0) {
							receivedRecords = true;
							progressBar.classList.remove('indeterminate');
							progressBar.classList.add('determinate');
						}
                        
                        if(receivedRecords == true)
                        {
                            const percentage = (status.currentRecord / status.maxRecord) * 100;
                            progressBar.style.width = `${percentage}%`;
                            recordCount.innerText = status.currentRecord + " of " + status.maxRecord;
                        }


                        statusText.innerText = status.statusText;

                        if (status.running) {
                            setTimeout(updateStatus, 300);
                        } else {
                        	if(receivedRecords == false) {
    							progressBar.classList.remove('indeterminate');
    							progressBar.classList.add('determinate');
							}
                        	
                            progressBar.style.width = '100%';
                            
                            if(status.exitStatus == 'OK') {
                            	progressBar.style.backgroundColor = 'green';
                                recordCount.innerText = 'Setup completed.';
                            	M.toast({html: 'Processing completed!'});
                            }								
							else
							{
								progressBar.style.backgroundColor = 'red';
								recordCount.innerText = 'Setup failed.';
                                M.toast({html: 'Processing failed!'});
							}
                            	
                        	
                           
                        }
                    }                
                    else {               
                        statusText.innerText = 'Error fetching status.';
                        setTimeout(updateStatus, 1000);
                    }
                } catch (error) {
                    console.error('Internal error:', error);
                    statusText.innerText = 'Internal error.';
                }
            };

            updateStatus();
        }
    </script>
</body>
</html>
