let serverPort = 3000;
const url = "http://transport.tallinn.ee/gps.txt";

const express = require('express');
const { fstat } = require('fs');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const axios = require('axios');
const fs = require('node:fs');
var sleep = require('sleep');

console.log("Server initalize!");

app.get('/', (req, res) => {
    console.log("Init root /");
    //index.html
    res.sendFile(__dirname + '/client/index.html');
});

server.listen(serverPort, () => {
    console.log("Apache server initalized...");
    console.log('Server started on port', serverPort);
    triggerDataFetch();
});

io.on('takSearch', (socket) => {
    
});

async function triggerDataFetch() {
    while (true) {
        console.log("Fetching new data...");
        await fetchData();
        console.log("Data fetch completed. Wait 5 seconds before next fetch!");
        await sleep.usleep(5000000);
    }
}

async function fetchData() {
    try {
        const response = await axios.get(url);
        if (response.status === 200) {
            const lines = response.data.split('\n');
            lines.forEach(line => {
                if (line) {
                    const data = line.split(',');
                    if (data.length >= 9) {
                        try {
                            const transportType = parseInt(data[0]);
                            const lineNumber = parseInt(data[1]);
                            const longitude = parseInt(data[2]) / 1000000;
                            const latitude = parseInt(data[3]) / 1000000;
                            const tak = data[6];

                            let transportTypeDecoded;
                            switch (transportType) {
                                case 1:
                                    transportTypeDecoded = "TROLL";
                                    break;
                                case 2:
                                    transportTypeDecoded = "BUS";
                                    break;
                                case 3:
                                    transportTypeDecoded = "TRAM";
                                    break;
                                default:
                                    transportTypeDecoded = "Unknown";
                                    break;
                            }
                            console.log("Transport Type:", transportTypeDecoded);
                            console.log("Line Number:", lineNumber);
                            console.log("Latitude:", latitude);
                            console.log("Longitude:", longitude);
                            console.log("Decoded address:");
                            console.log("TAK:", tak);
                            console.log();
                        } catch (error) {
                            console.log("Invalid data format!", line);
                        }
                    }
                }
            });
        } else {
            console.log("Data fetch fail! Got status:", response.status);
        }
    } catch (error) {
        console.error("Error fetching data:", error);
    }
}




















<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bus Location Finder</title>
  <style>
    #map {
      height: 1000px;
      width: 100%;
    }
  </style>
</head>
<body>

<h2>Bus Location Finder</h2>
<form id="search-form">
  <label for="bus-id">Enter Bus ID (TAK):</label>
  <input type="text" id="bus-id" name="bus-id">
  <button type="submit">Search</button>
</form>

<div id="map"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css" />

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();

  // Stuff for the map
  var map = L.map('map').setView([59.4370, 24.7536], 12);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  // Function to handle form submission
  document.getElementById('search-form').addEventListener('submit', function(event) {
    var tak = document.getElementById('bus-id').value.trim();
    socket.emit('takSearch', tak);
  });

</script>

</body>
</html>




















let serverPort = 3000;
const url = "http://transport.tallinn.ee/gps.txt";

const express = require('express');
const { fstat } = require('fs');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const axios = require('axios');
const fs = require('node:fs');
var sleep = require('sleep');

console.log("Server initalize!");

app.get('/', (req, res) => {
    console.log("Init root /");
    //index.html
    res.sendFile(__dirname + '/client/index.html');
});

server.listen(serverPort, () => {
    console.log("Apache server initalized...");
    console.log('Server started on port', serverPort);
    //triggerDataFetch();
});

io.on('connection', (socket) => {
    console.log("Got connection from user! Waiting for taksearch...")
    socket.on('takSearch', (tak) => {
        console.log(tak);
        console.log(triggerDataFetch(tak));
    });
});

function triggerDataFetch(tak) {
    console.log("Fetching new data...");
    const data = fetchData();
    console.log("Data fetch completed.");
    const filteredData = data.filter(item => item.tak === tak);
    return filteredData;
    //await io.emit('takSearch', filteredData);
    // this part is only for when it is continuous
    //console.log("Data fetch completed. Wait 5 seconds before next fetch!");
    //await sleep.usleep(5000000);
    // also add while true cycle
}

function fetchData() {
    try {
        const response = axios.get(url);
        if (response.status == 200) {
            const lines = response.data.split('\n');
            const result = [];
            lines.forEach(line => {
                if (line) {
                    const data = line.split(',');
                    if (data.length >= 9) {
                        try {
                            const transportType = parseInt(data[0]);
                            const lineNumber = parseInt(data[1]);
                            const longitude = parseInt(data[2]) / 1000000;
                            const latitude = parseInt(data[3]) / 1000000;
                            const tak = data[6];

                            let transportTypeDecoded;
                            switch (transportType) {
                                case 1:
                                    transportTypeDecoded = "TROLL";
                                    break;
                                case 2:
                                    transportTypeDecoded = "BUS";
                                    break;
                                case 3:
                                    transportTypeDecoded = "TRAM";
                                    break;
                                default:
                                    transportTypeDecoded = "Unknown";
                                    break;
                            }

                            result.push({
                                transportType: transportTypeDecoded,
                                lineNumber,
                                longitude,
                                latitude,
                                tak
                            });
                        } catch (error) {
                            console.log("Invalid data format!", line);
                        }
                    }
                }
            });
            return result;
        } else {
            console.log("Data fetch fail! Got status:", response.status);
            return [];
        }
    } catch (error) {
        console.error("Error fetching data:", error);
        return [];
    }
}