package me.koba1.led.utils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class KobaLogger {

    private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");

    private final File file;
    private BufferedWriter writer;

    public KobaLogger() {
        this.file = Utils.getFile(new File("log.txt"));
        try {
            this.writer = new BufferedWriter(new FileWriter(this.file, true), 8192);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void info(String message) {
        System.out.println(message);
        try {
            this.writer.write("[" + FORMAT.format(LocalDateTime.now()) + "] ");
            this.writer.write(message);
            this.writer.newLine();
            this.writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void error(String message) {
        System.out.println("[ERR] " + message);
        try {
            this.writer.write("[" + FORMAT.format(LocalDateTime.now()) + "] [ERR] ");
            this.writer.write(message);
            this.writer.newLine();
            this.writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void clear() {
        try {
            this.writer.close();
            new FileWriter(this.file, false).close();
            this.writer = new BufferedWriter(new FileWriter(this.file, true), 8192);
        } catch (IOException ignored) {}
    }

    public List<String> getMessages() {
        List<String> messages = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(this.file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                messages.add(line);
            }
            return messages;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
