const net = require('net');

const {
  GITKRAKEN_SOCKET_SERVICE_PORT,
  GITKRAKEN_GIT_SEQUENCE_EDITOR_DOMAIN
} = process.env;

const performHandshake = (clientSocket) =>
  new Promise((resolve, reject) => {
    clientSocket.on('error', reject);
    clientSocket.on('close', reject);
    clientSocket.on('end', reject);

    clientSocket.once('data', (data) => {
      clientSocket.removeListener('error', reject);
      clientSocket.removeListener('close', reject);
      clientSocket.removeListener('end', reject);

      if (data.toString() !== 'ready') {
        reject();
      } else {
        resolve();
      }
    });

    clientSocket.write(GITKRAKEN_GIT_SEQUENCE_EDITOR_DOMAIN);
  });

const performRequest = (onData, request) => {
  const client = net.createConnection(
    {
      port: Number.parseInt(GITKRAKEN_SOCKET_SERVICE_PORT ?? '', 10),
      host: '127.0.0.1'
    },
    async () => {
      try {
        await performHandshake(client);
      } catch (error) {
        process.exit(1);
      }

      client.on('error', () => {
        process.exit(1);
      });
      client.on('end', () => {
        process.exit(1);
      });

      client.on('data', (data) => {
        try {
          onData(data);
        } catch (error) {
          process.exit(1);
        }
      });
      client.write(`${request}\0`);
    }
  );
};

const onDataFunction = (data) => {
  const { c: exitCode } = JSON.parse(data.toString());
  process.exit(exitCode);
};

const processedArgs = () => {
  const filePathToClose = process.argv[2];
  return JSON.stringify({ filePathToClose });
};

performRequest(onDataFunction, processedArgs());
