import { SignaldAPI, CaptchaRequiredException } from "node-signald";
import * as process from "process";
import * as prompt from "prompt";

const SOCKETFILE =
  process.env.SIGNALD_SOCKET || "/run/user/1000/signald/signald.sock";

const validate = () => {
  if (!process.env.NUMBER)
    throw new Error(
      "Please set the NUMBER env var to the number you want to test with."
    );
};
const main = async () => {
  validate();
  const signald = new SignaldAPI();
  await signald.connectAsync(SOCKETFILE);
  try {
    await signald.register(process.env.NUMBER);
  } catch (e) {
    console.log("GOT A error", e.name);
    if (e.name === "CaptchaRequiredException") {
      console.log(`

CAPTCHA REQUIRED
-----------------

1. Visit https://signalcaptchas.org/registration/generate.html
2. Appease the machine
3. Bring back your captcha gobbly-gook here
`);
      console.log("captcha required");

      prompt.start();
      const { captcha } = await prompt.get(["captcha"]);
      await signald.register(process.env.NUMBER, false, captcha);
    } else {
      console.error(e);
    }
  }

  const { code } = await prompt.get(["code"]);
  await signald.verify(process.env.NUMBER, code);
};

const main2 = async () => {
  validate();
  const signald = new SignaldAPI();
  await signald.connectAsync(SOCKETFILE);
  let result = await signald.listAccounts();
  console.log(JSON.stringify(result));
  signald.on("messagev0", (envelope) => {
    const source = envelope.source.number;
    const body = envelope.dataMessage.body;
    const when = new Date(envelope.timestamp).toDateString();
    console.log(`${when} [${source}]: ${body}`);
  });

  await Promise.all(
    result.accounts.map(
      async (account: any) => await signald.requestSync(account.address.uuid)
    )
  );

  await Promise.all(
    result.accounts.map(
      async (account: any) => await signald.subscribev0(account.address.uuid)
    )
  );
};

// main();
main2();
