File size: 30,428 Bytes
829f2ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
var selectElement = document.getElementById('languages');

// Initialize the variable with the default selected option
var lang = selectElement.value;
var started = false;
var continueExecution = true;
var displayText = {};
var previousquery = "";

// Call the function to fetch the data and save it in a variable
(async () => {
    try {
        const response = await fetch('/static/data/displayText.json');
        displayText = await response.json();
    } catch (error) {
        console.error('Error fetching data:', error);
        return null;
    }
})();

function destruct() {
    document.getElementsByTagName('progress')[0].style.display = "none";
    document.getElementsByTagName('progress')[0].value = 0;

    document.getElementsByClassName('progressMessage')[0].innerHTML = "";
    document.getElementsByClassName('progressMessage')[0].classList.remove("update-progressMessage");

    document.getElementById("map_html").srcdoc = "";

    document.getElementsByClassName("conclusion-container")[0].innerHTML = "<h3>Result:</h3>";
    document.getElementsByClassName("result-container")[0].style.display = "none";

    for (let audio in document.getElementsByTagName('audio')) {
        audio.innerHTML = "";
    }
    started = false;
    previousquery = ""
}

// Add a 'change' event listener to the <select> element
selectElement.addEventListener('change', function () {
    // Update the variable when the selection changes
    lang = selectElement.value;
    destruct();
    // Store the selected language in localStorage
    localStorage.setItem('selectedLanguage', lang);
    var langQueries = "";
    for (let query of displayText[lang]['queries']) {
        langQueries += `<option value="${query}"></option>`;
    }
    document.getElementById("queries").innerHTML = langQueries;

    document.getElementById("user_text").placeholder = displayText[lang]['enter'];
    document.getElementById("submitBtn").innerHTML = displayText[lang]['run'];
    micIcon.src = "/static/assets/micplay.svg";
    document.getElementById("error").innerHTML = "";
    // Log the updated selected option to the console (optional)
    console.log('Selected Option:', lang);

    document.getElementById('user_text').value = "";
    destruct();
});

const user_text = document.getElementById('user_text');
const suggestionBox = document.getElementById('suggestion-box');
let lastInputLength = 0; // Track input length for deletion handling

document.getElementById('checkbox_toggle').addEventListener('change', async function () {
    if (this.checked) {
        const response = await fetch('/start_webcam', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });
        interative_mode = true;

        console.log(await response.json());
    } else {
        const response = await fetch('/stop_webcam', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });
        interative_mode = false;

        console.log(await response.json());
    }
});

user_text.addEventListener('input', async function () {
    const text = this.value;

    if ((lang != 'english') && text.length > 0) {
        // Handle backspace/deletion:
        if (text.length < lastInputLength) {
            suggestionBox.style.display = 'none'; // Hide suggestions on deletion
            lastInputLength = text.length; // Update tracking
            return; // No need to fetch suggestions again
        }

        // Handle regular input or text growth:
        lastInputLength = text.length; // Update tracking

        try {
            const response = await fetch('/transliterate', {
                method: 'POST',
                body: JSON.stringify({ 'text': text, 'lang': lang }),
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();
            const suggestions = data.translation;

            if (suggestions.length > 0) {
                suggestionBox.innerHTML = suggestions.map(suggestion =>
                    `<div class="suggestion">${suggestion}</div>`
                ).join('');
                suggestionBox.style.display = 'block'; // Show suggestions
            } else {
                suggestionBox.style.display = 'none'; // Hide suggestions if none found
            }
        } catch (error) {
            console.error(error);
            suggestionBox.style.display = 'none'; // Hide suggestions in case of errors
        }
    } else {
        suggestionBox.style.display = 'none'; // Hide suggestions if empty text or non-Hindi
    }
});

user_text.addEventListener('focus', async function () {
    console.log(document.getElementById('checkbox_toggle').checked);

    if (document.getElementById('checkbox_toggle').checked) {
        const response = await fetch('/start_sign', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });

        console.log(await response.json());

        async function fetchTypedText() {
            const response = await fetch('/typed_text', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });
            var result = await response.json();
            console.log(result);

            if (result['typed_text'] != "") {
                user_text.value = result['typed_text'];
            }
        }

        if (interative_mode) {
            setInterval(fetchTypedText, 1000);
        }
    }
});

suggestionBox.addEventListener('click', function (event) {
    const clickedSuggestion = event.target.closest('.suggestion');
    if (clickedSuggestion) {
        user_text.value = clickedSuggestion.textContent;
        suggestionBox.style.display = 'none'; // Hide suggestions after selection
    }
});

function removeChildrens() {
    document.getElementsByTagName('progress')[0].style.display = "none";
    document.getElementById("myForm").removeChild(document.getElementsByClassName('progressMessage')[0]);

    for (let step = 1; step <= 7; step++) {
        document.getElementById("myForm").removeChild(document.getElementById("step" + step));
    }
}

function restoreChildrens() {
    var progressMessage = document.createElement("div");
    progressMessage.className = "progressMessage";
    document.getElementById("myForm").appendChild(progressMessage);

    for (let step = 1; step <= 7; step++) {
        var progressPlayer = document.createElement("audio");
        progressPlayer.id = "step" + step;
        document.getElementById("myForm").appendChild(progressPlayer);
    }
}

function reloadAndRunQuery() {
    // Store the query in localStorage to retain it after the reload
    localStorage.setItem('queryToRun',);

    // Reload the page
    location.reload();
}
async function mapCall(selected_roi_name, lang, start_date, end_date) {
    previousQuery = user_text.value;
    console.log(previousQuery);
    console.log(selected_roi_name, lang, start_date, end_date);
    // Store the query and reload the page
    localStorage.setItem('queryToRun', JSON.stringify({
        selected_roi_name, lang, start_date, end_date
    }));
    localStorage.setItem('previousQuery', previousQuery);
    location.reload();
}

window.onload = async function () {
    // Retrieve stored language from localStorage
    const storedLanguage = localStorage.getItem('selectedLanguage');
    const selectElement = document.getElementById('languages'); // Assuming you have a select element for languages

    if (storedLanguage && selectElement) {
        // Set the stored language as the selected option
        selectElement.value = storedLanguage;
        lang = storedLanguage;  // Update the global 'lang' variable

        // Update the language-specific queries and UI
        var langQueries = "";
        if (displayText[lang] && displayText[lang]['queries']) {
            for (let query of displayText[lang]['queries']) {
                langQueries += `<option value="${query}"></option>`;
            }
            const queriesElement = document.getElementById("queries");
            if (queriesElement) {
                queriesElement.innerHTML = langQueries;
            }
        }

        const userTextElement = document.getElementById("user_text");
        const submitBtnElement = document.getElementById("submitBtn");
        const micIcon = document.getElementById("micIcon"); // Assuming you have an element for mic icon

        if (userTextElement && submitBtnElement && micIcon) {
            userTextElement.placeholder = displayText[lang]['enter'];
            submitBtnElement.innerHTML = displayText[lang]['run'];
            micIcon.src = "/static/assets/micplay.svg";
            document.getElementById("error").innerHTML = "";
        }
    }

    // Check if there's a query stored in localStorage
    const queryToRun = localStorage.getItem('queryToRun');
    const storedQuery = localStorage.getItem('previousQuery');

    if (storedQuery) {
        // Set the stored query as the value of the input tag
        const userTextElement = document.getElementById('user_text');
        if (userTextElement) {
            userTextElement.value = storedQuery;
            localStorage.removeItem('previousQuery');
        }
    }

    if (queryToRun) {
        // Parse the stored query
        const { selected_roi_name, lang, start_date, end_date } = JSON.parse(queryToRun);
        localStorage.removeItem('queryToRun');

        // Run the query with the selected language
        await runQuery(selected_roi_name, lang, start_date, end_date);
    }
}

async function runQuery(selected_roi_name, lang, start_date, end_date) {
    // Clear any previous results or processes
    destruct();

    const loaderElement = document.getElementById('loader');
    if (loaderElement) {
        loaderElement.style.display = 'block';
    }

    // Perform the fetch request
    let res = await fetch('/map', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'selected_roi_name': selected_roi_name,
            'lang': lang,
            'start_date': start_date,
            'end_date': end_date
        })
    });
    let data = await res.json();

    if (data['status'] === 'ok') {
        document.getElementById('loader').style.display = 'none';
        const progressElement = document.getElementsByTagName('progress')[0];
        if (progressElement && progressElement.style.display === "none") {
            restoreChildrens();
            showProgressBar("");
        }

        const chart_file_path = data['chart_file_path'];
        document.getElementById('loader').style.display = 'none';
        const mapHtmlElement = document.getElementById("map_html");
        if (mapHtmlElement) {
            mapHtmlElement.srcdoc = data['map_html'];
        }

        const conclusionContainer = document.getElementsByClassName("conclusion-container")[0];
        if (conclusionContainer) {
            data['conclusion'].split('. ').forEach((sentence) => {
                let p = document.createElement("p");
                p.innerHTML = sentence + ". ";
                conclusionContainer.appendChild(p);
            });
        }

        // Set the source dynamically using JavaScript
        var source = document.createElement("source");
        source.src = data['conclusion_file_path'];
        source.type = "audio/mp3";

        const audioConclusion = document.getElementById("audioConclusion");
        if (audioConclusion) {
            audioConclusion.appendChild(source);
        }

        previousquery = user_text.value;

        if (chart_file_path !== "") {
            addChart(selected_roi_name, chart_file_path);

            var response = await fetch('/timelapse', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    'selected_roi_name': selected_roi_name
                })
            });

            const timelapse = await response.json();

            const container = document.getElementById('timeLapse');
            if (container) {
                container.src = timelapse['video_thumb_url'];
            }

        }
    } else {
        const progressElement = document.getElementsByTagName('progress')[0];
        if (progressElement && progressElement.style.display !== "none") {
            removeChildrens();
        }
        continueExecution = false;

        if (data['status'] === "") {
            document.getElementById("error").innerHTML = data['error'];
        } else {
            const doyouwant = data['status'];
            var selectionContent = document.getElementById('select-prompt');

            const promptElement = document.getElementById("prompt");
            if (promptElement) {
                promptElement.style.display = "block";

                let index = 0;

                function addCharacter() {
                    if (index < doyouwant.length) {
                        continueExecution = false;
                        selectionContent.innerHTML += doyouwant.charAt(index);
                        index++;
                        setTimeout(addCharacter, 40);
                    } else {
                        const promptContainer = document.getElementsByClassName("prompt-container")[0];
                        if (promptContainer) {
                            promptContainer.style.display = "flex";
                            setTimeout(() => {
                                promptElement.style.display = "none";
                            }, 15000);
                        }
                    }
                }

                addCharacter();

                var source = document.createElement("source");
                source.src = data['conclusion_file_path'];
                source.type = "audio/mp3";

                const doyoumeanElement = document.getElementById("doyoumean");
                if (doyoumeanElement) {
                    doyoumeanElement.appendChild(source);
                    doyoumeanElement.play();
                }

                const yesButton = document.getElementById("yes-button");
                const noButton = document.getElementById("no-button");

                if (yesButton) {
                    yesButton.addEventListener('click', () => {
                        try {
                            promptElement.style.display = "none";
                            mapCall(selected_roi_name, lang, data['conclusion'], end_date);
                        } catch (error) {
                            console.error('An error occurred:', error);
                        }
                    });
                }

                if (noButton) {
                    noButton.addEventListener('click', () => {
                        try {
                            location.reload();
                        } catch (error) {
                            console.error('An error occurred:', error);
                        }
                    });
                }
            }
        }
    }
}


document.addEventListener('DOMContentLoaded', () => {
    const micIcon = document.getElementById('micIcon');
    const submitBtn = document.getElementById('submitBtn');
    let isRecording = false;
    let audio_text = "";

    // Start or stop recording on button click
    micIcon.addEventListener('click', async () => {
        if (isRecording) {
            micIcon.src = "/static/assets/micplay.svg";
            console.log("Recording paused");
        } else {
            micIcon.src = "/static/assets/micpause.svg";
            console.log(lang);

            var source = document.createElement("source");
            source.src = "static/audio/languages/" + lang + "/ask.mp3";
            source.type = "audio/mp3";

            document.getElementById("audioPlayer").appendChild(source);
            document.getElementById("audioPlayer").play();

            console.log("started");
        }

        // isRecording = !isRecording;

        if (!isRecording) {
            isRecording = true;
            document.getElementById("error").innerHTML = "";
        } try {
            const response = await fetch('/startstop', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    'lang': lang,
                    'type_audio': isRecording ? "start" : "stop"
                })
            });

            if (isRecording) {
                const data = await response.json();
                audio_text = data['message'];
                error = data['error'];

                document.getElementById("error").innerHTML = error;

                if (error == "") {
                    user_text.value = audio_text;
                }

                micIcon.src = "/static/assets/micplay.svg";
                isRecording = false;
            }
        } catch (error) {
            micIcon.src = "/static/assets/micplay.svg";
            console.log("paused");
            isRecording = false;

            console.error('Error sending request:', error);
        }
    
    });

    submitBtn.addEventListener('click', async (event) => {
        destruct();
        document.getElementById('loader').style.display = 'block';
        event.preventDefault();
        const user_textElement = document.getElementById("user_text");
        if (!user_textElement) {
            console.error("Element with id 'user_text' not found.");
            document.getElementById("error").innerHTML = "Input field not found.";
            document.getElementById('loader').style.display = 'none';
            return;
        }
        const user_text = user_textElement.value.trim();
        const query = user_text || audio_text;

        if (!query) {

            const errorMessages = {
                english: "Please enter a query.",
                hindi: "कृपया एक प्रश्न दर्ज करें।",
                telugu: "దయచేసి ఒక ప్రశ్న నమోదు చేయండి.",
                malayalam: "ദയവായി ഒരു ചോദ്യം നൽകുക.",
                marathi: "कृपया एक प्रश्न प्रविष्ट करा.",
                tamil: "தயவுசெய்து கேள்வியை உள்ளிடவும்.",
                gujarati: "કૃપા કરીને એક પ્રશ્ન દાખલ કરો.",
                bengali: "দয়া করে একটি প্রশ্ন লিখুন।",
                kannada: "ದಯವಿಟ್ಟು ಒಂದು ಪ್ರಶ್ನೆ ನಮೂದಿಸಿ."
            };

            document.getElementById("error").innerHTML = errorMessages[lang] || errorMessages['en'];
            document.getElementById('loader').style.display = 'none';
            setTimeout(() => {
                location.reload();
             }, 5000);
            return;
        }

        try {
            const formData = new FormData(document.getElementById('myForm'));
            formData.set('lang', lang);
            formData.set('user_text', query); // Ensure that text/audio input is sent

            const response = await fetch('/', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();

            if (data.selection) {

                // Process response data (like date handling, map rendering, etc.)
            if (data.selected_roi_name) {
                const res = await fetch('/date', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        'user_text': query,
                        'lang': lang
                    })
                });

                
                //mapCall(data.selected_roi_name, lang, dateData.start_date, dateData.end_date);
           
                const dateData = await res.json();
                showSelectionPrompt(data,dateData,data.selection);
                var source = document.createElement("source");
                source.src = data['audio_file_path'];
                source.type = "audio/mp3";

                document.getElementById("doyoumean").appendChild(source);
                document.getElementById("doyoumean").play();

            }}
            else{

            if (data.selected_roi_name) {
                const res = await fetch('/date', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        'user_text': query,
                        'lang': lang
                    })
                });
                const dateData = await res.json();
                mapCall(data.selected_roi_name, lang, dateData.start_date, dateData.end_date);
            }
        }    
            

        } catch (error) {
            console.error('Error processing request:', error);
        } finally {
            document.getElementById('loader').style.display = 'none';
        }
    });
});

function showSelectionPrompt(data,dateData,selectionText) {
    const selectionContent = document.getElementById('select-prompt');
    selectionContent.innerHTML = '';

    document.getElementById('loader').style.display = 'none';
    document.getElementById("prompt").style.display = "block";

    let index = 0;

    

    function addCharacter() {
        if (index < selectionText.length) {
            selectionContent.innerHTML += selectionText.charAt(index);
            index++;
            setTimeout(addCharacter, 40);
        } else {
            document.getElementsByClassName("prompt-container")[0].style.display = "flex";
            
            setTimeout(() => {
                document.getElementById("prompt").style.display = "none";
                const errorMessages = {
                    english: "Please provide input.",
                    hindi: "कृपया इनपुट प्रदान करें।",
                    telugu: "దయచేసి ఇన్‌పుట్ ఇవ్వండి.",
                    malayalam: "ദയവായി ഇൻപുട്ട് നൽകുക.",
                    marathi: "कृपया इनपुट द्या.",
                    tamil: "தயவுசெய்து உள்ளீட்டை வழங்கவும்.",
                    gujarati: "કૃપા કરીને ઇનપુટ પ્રદાન કરો.",
                    bengali: "দয়া করে ইনপুট দিন।",
                    kannada: "ದಯವಿಟ್ಟು ಇನ್‌ಪುಟ್ ಒದಗಿಸಿ."
                };
                document.getElementById("error").innerHTML = errorMessages[lang] || errorMessages['en'];
                
                setTimeout(() => {
                    location.reload();
                 }, 5000);
            }, 15000);

            


        }
    }

    addCharacter();

    document.getElementById("yes-button").addEventListener('click', () => {
        try {
            document.getElementById("prompt").style.display = "none";
        } catch (error) {
            console.error('An error occurred:', error);
        }
        console.log("NRSC")
        mapCall(data.selected_roi_name, lang, dateData.start_date, dateData.end_date);
    });

    document.getElementById("no-button").addEventListener('click', () => {
        try{
            location.reload();
        } catch(error) {
            console.error('An error occurred:', error);
        }
    });


}

function showProgressBar(audio_text) {
    var progressBar = document.getElementsByTagName('progress')[0];
    var progressMessage = document.getElementsByClassName('progressMessage')[0];
    progressMessage.classList.add("update-progressMessage");
    progressBar.style.display = "block";
    progressBar.value = 0;

    var query = user_text.value;

    if (query == "") {
        query = audio_text;
    }

    var steps = [
        { percent: 10, message: displayText[lang]['steps'][0] },
        { percent: 20, message: `${displayText[lang]['query']} ${query}` },
        { percent: 30, message: displayText[lang]['steps'][1] },
        { percent: 40, message: displayText[lang]['steps'][2] },
        { percent: 60, message: displayText[lang]['steps'][3] },
        { percent: 80, message: displayText[lang]['steps'][4] },
        { percent: 100, message: displayText[lang]['steps'][5] }
    ];

    for (let step = 1; step <= 7; step++) {
        var source = document.createElement("source");
        source.src = "/static/audio/languages/" + lang + "/step" + step + ".mp3";
        source.type = "audio/mp3";

        var progressPlayer = document.getElementById("step" + step);
        progressPlayer.appendChild(source);
    }

    var currentStep = 0;

    function updateProgressBar() {
        progressBar.value = steps[currentStep].percent;
        var currentMessage = steps[currentStep].message;
        var index = 0;

        function appendCharacter() {
            if (index < currentMessage.length) {
                document.getElementById("step" + (currentStep + 1)).play();
                progressMessage.innerHTML += currentMessage.charAt(index);
                index++;
                setTimeout(appendCharacter, 30); // Adjust the timeout as needed
            } else {
                progressMessage.innerHTML += "<br/><br/>";
                if (currentStep < steps.length - 1) {
                    document.getElementById("step" + (currentStep + 1)).onended = function () {
                        currentStep++;
                        updateProgressBar();
                    };
                } else {
                    currentStep++;
                }

                if (currentStep == steps.length) {
                    document.getElementById("step" + (currentStep)).onended = function () {
                        document.getElementsByClassName("result-container")[0].style.display = "block";
                        document.getElementById("audioConclusion").play();
                    };
                }
            }
        }

        appendCharacter();
    }
    updateProgressBar();
}

function addChart(selected_roi_name, chart_file_path) {
    async function loadChartData() {
        try {
            const response = await fetch(chart_file_path);
            if (!response.ok) {
                throw new Error(`Failed to fetch chart data: ${response.statusText}`);
            }
            return await response.json();
        } catch (error) {
            console.error('Error loading chart data:', error);
            return null;
        }
    }

    async function createChart() {
        try {
            const chartData = await loadChartData();
            if (!chartData) {
                throw new Error('Failed to load chart data.');
            }

            const dates = chartData.map(item => moment(item.Date).format('MMM DD, YYYY'));
            const waterPixelCounts = chartData.map(item => item['Water Pixel Count']);

            document.getElementById('myChart').style.display = "block";

            // Create chart
            const ctx = document.getElementById('myChart').getContext('2d');
            Chart.defaults.global.defaultFontColor = 'white';
            const myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: dates,
                    datasets: [{
                        label: `Water Spread of ${selected_roi_name}`,
                        data: waterPixelCounts,
                        backgroundColor: waterPixelCounts.map(count => {
                            if (count === Math.min(...waterPixelCounts)) {
                                return 'rgba(255, 0, 0, 1)'; // Red for minimum
                            } else if (count === Math.max(...waterPixelCounts)) {
                                return 'rgba(0, 255, 0, 1)'; // Green for maximum
                            } else {
                                return 'rgba(255, 165, 0, 0.2)';
                            }
                        }),
                        borderColor: '#FFA500',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false, // Disable default aspect ratio to allow custom width and height
                    maxWidth: 900,
                    maxHeight: 600,
                    scales: {
                        yAxes: [{
                            scaleLabel: {
                                display: true,
                                labelString: "Water Area in square kilometers",
                                fontColor: "#FFFFFF"
                            },
                            ticks: {
                                fontColor: "#FFFFFF"
                            }
                        }],
                        xAxes: [{
                            scaleLabel: {
                                display: true,
                                labelString: "Date",
                                fontColor: "#FFFFFF"
                            },
                            ticks: {
                                fontColor: "#FFFFFF"
                            }
                        }]
                    },
                    plugins: {
                        legend: {
                            labels: {
                                font: {
                                    size: 12
                                },
                                labelColor: "#FFFFFF"
                            }
                        }
                    }
                }
            });

        } catch (error) {
            console.error('Error creating chart:', error);
        }
    }

    createChart();
}