package com.its.vds.stat.server;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
class VdsStatServerApplicationTest {

    @Test
    void test1() {
        CronSchedulerHelper helper = new CronSchedulerHelper();

        String cronExpr = "10 * * * * *";  // 매분 10초
        Duration interval = helper.estimateInterval(cronExpr);
        System.out.println("Estimated Interval: " + interval.getSeconds() + " seconds");

        cronExpr = "10/30 * * * * *";  // 매분 10초, 30초
        interval = helper.estimateInterval(cronExpr);
        System.out.println("Estimated Interval: " + interval.getSeconds() + " seconds");

        cronExpr = "0 */5 * * * *";  // 매 5분마다 실행
        interval = helper.estimateInterval(cronExpr);
        System.out.println("Estimated Interval: " + interval.getSeconds() + " seconds");

        List<ZonedDateTime> nextRuns = helper.getNextExecutions(cronExpr, 5);
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        System.out.println("Next Execution Times:");
        for (ZonedDateTime run : nextRuns) {
            System.out.println(" - " + run.format(fmt));
        }
    }

    public void doCommand(List<String> command) throws IOException {
        String s = null;

        ProcessBuilder pb = new ProcessBuilder(command);
        Process process = pb.start();

        Charset charset = Charset.forName("MS949");

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(), charset));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream(), charset));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            log.info(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            log.error(s);
        }
    }

    @Test
    void test2() throws IOException {
        List<String> commands = new ArrayList<String>();
        commands.add("ping");
        commands.add("-n");
        commands.add("5");
        commands.add("74.125.236.73");
        doCommand(commands);
    }
}