// Install ws package first by running: npm install ws protobufjs zlib
const WebSocket = require('ws');
const protobuf = require('protobufjs');
const path = require('path');
const zlib = require('zlib');
const AddData = require("./AddData");
const { connect } = require('http2');
const { Sema } = require('async-sema');
const { valid } = require('generate-object-property');
const fs = require('fs');
//temp
// const Connection = require('../DB/Connection');
// let con = new Connection()
//end temp

//
// Load the compiled protobuf file
const root = protobuf.loadSync(path.resolve(__dirname, "test3.proto"));
const Person = root.lookupType('Person');

// Create WebSocket server
const wss = new WebSocket.Server({ port: 30000 }, () => {
    console.log('WebSocket server is listening on port 30000');
});

//v2

let archive = "archive"
let polytb = "polytunnels";
let polyLinetb = "poly_lines";
let trapstb = "traps";
let scantb = "Scans";
wss.on('connection', async (ws) => {
    console.log('Client connected');
    let addD = new AddData();
    console.log("connected now");
    let collectPolyT = []
    let collectPolyLine = []
    let collectTrap = []
    let collectScan = []
    let holdTb = ""
    //const sema = new Sema(0); 

    //addD.wStart()


     ws.on('message', (message) => {
        const buffer = Buffer.from(message);
        try {
            console.log("compressed size: ", buffer.length);
            const decompressedBuffer = zlib.inflateRawSync(buffer);
            const decodedData = Person.decode(decompressedBuffer);

            console.log("decompressed size: ", decodedData.length);

            // Convert the protobuf data to JSON format
            const jsonData = Person.toObject(decodedData, { enums: String, longs: String, bytes: String, defaults: true });
             console.log('Decoded Data:', jsonData);  //in use
 

            if(jsonData.data[0] == "ping")
            {
                console.log('Decoded Data:', jsonData);  //in use

                ws.send(JSON.stringify("pong"))
                console.log("sent")
                return 
            }

          //  if(1==1) { return; } //test for android
            if(jsonData.data[0] == polytb || jsonData.data[0] == polyLinetb || jsonData.data[0] == trapstb ||
                jsonData.data[0] == scantb || jsonData.data[0] == polyLinetb || jsonData.data[0] == archive || jsonData.data[0] == "valid"
            ) 
            { holdTb = jsonData.data[0] }

            if(holdTb == archive)
            {
                addD.importData(jsonData, ws)
            }
            else if(holdTb == polytb) 
            {
                collectPolyT.push(jsonData)
               // addD.addPolyTunnel(collectPolyT, ws);
                //collectPolyT = []
                //console.log("tunnels : ", collectPolyT)

            }
            else if(holdTb == polyLinetb) { 
                if(collectPolyT.length > 0)
                {
                    addD.addPolyTunnel(collectPolyT, ws);
                    collectPolyT = []
                }
                 collectPolyLine.push(jsonData)
               }
            else if(holdTb == trapstb)
            {
                if(collectPolyLine.length > 0) {
                    addD.addLine(collectPolyLine, ws)
                    collectPolyLine = []
                }
                collectTrap.push(jsonData)
            }
            else if(holdTb == scantb)
            {
                if(collectTrap.length > 0)
                {
                   addD.addTrap(collectTrap, ws);
                   collectTrap = []
                }
               // console.log("scan pending ", jsonData)

               // collectTrap = [];
                collectScan.push(jsonData)
             //   console.log("scan pending ", collectScan)

                addD.addScan(collectScan, ws);
                collectScan = []
            }
            else if(holdTb == "valid")
            {
                console.log("table check ", holdTb)

                addD.sendValid(ws)
            }
         //   ws.send(JSON.stringify({ status: "received", type: "archive" })); // Add response

        } catch (err) {
            console.error('Failed to decode protobuf data:', err);
            ws.send('Failed to decode protobuf data');
        }
    });
    //console.log("lines: ", collectPolyLine)

    ws.on('close', () => {
        console.log('Client disconnected');
    });
    ws.on('error', (error) => {
        console.error('WebSocket error:', error);
    });
});
