const smpp = require("smpp");

const PORT = 2775;

let messageIdIterator = Math.floor(Math.random() * 1_000_000);
console.log(`Using iterator: ${messageIdIterator}`);

const server = smpp.createServer(
	{
		debug: false,
	},
	function (session) {
		session.on("error", function (err) {
			console.error(err);
		});
		session.on("bind_transceiver", function (pdu) {
			console.log("Client connected");
			session.send(pdu.response());
		});
		session.on("enquire_link", function (pdu) {
			session.send(pdu.response());
		});
		session.on("submit_sm", async function (pdu) {
			console.log(new Date().toISOString() + " Incoming submit_sm");
			console.log(pdu);
			let response = pdu.response();
			response.message_id = (messageIdIterator++).toString(16);
			session.send(response);

			let drMessage = "";
			let date = new Date()
				.toISOString()
				.replace(/T/, "")
				.replace(/\..+/, "")
				.replace(/-/g, "")
				.replace(/:/g, "")
				.substring(2, 12);

			drMessage += "id:" + response.message_id + " ";
			drMessage += "sub:001 ";
			drMessage += "dlvrd:001 ";
			drMessage += "submit date:" + date + " ";
			drMessage += "done date:" + date + " ";
			drMessage += "stat:DELIVRD ";
			drMessage += "err:000 ";
			drMessage += "text:";

			setTimeout(() => {
				console.log(new Date().toISOString() + " Sending DR");
				const DRPdu = {
					source_addr: pdu.source_addr,
					destination_addr: pdu.destination_addr,
					short_message: drMessage,
					esm_class: 4,
				};
				console.log(DRPdu);
				session.deliver_sm(DRPdu);
			}, 2 * 60 * 1000);
		});
	}
);

server.listen(PORT);
console.log("Server started");
