package fr.uge.concurrence;

import java.util.concurrent.ThreadLocalRandom;

public class CodeAPI {

    public static class DecodeException extends Exception {
        private static final long serialVersionUID = 1L;

        public DecodeException(String msg) {
            super(msg);
        }
    }

    public static String receive() throws InterruptedException {
        Thread.sleep(100);
        return "Coded : " + ThreadLocalRandom.current().nextInt(10000);
    }

    public static String decode(String codedMsg) throws InterruptedException, DecodeException {
        Thread.sleep(300);
        if (!codedMsg.startsWith("Coded : ")) {
            throw new IllegalArgumentException("decode can only be applied to coded messages");
        }
        var number = Integer.parseInt(codedMsg.substring(8));
        if (number > 5000) {
            throw new DecodeException("Decode error");
        }
        return "Decoded : " + number;
    }

    public static void archive(String decodedMsg) throws InterruptedException {
        Thread.sleep(50);
        IO.println("Archiving : " + decodedMsg);
    }
}