package org.example;
import com.github.freva.asciitable.AsciiTable;
import com.github.freva.asciitable.Column;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
public class Main {
    private static ArrayList<Swap> orders;
    private static Date date;
    private static ArrayList<ArrayList<Comparable>> rows;
    public static JSONArray getJsonArray_a() throws IOException {
        URL url = new URL("...");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.addRequestProperty("content-type", "application/json");
        connection.addRequestProperty("x-api-key", "...");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        PrintWriter writer = new PrintWriter(connection.getOutputStream());
        writer.println("{\"currency\":\"ALGO\",\"codes\":[\"ALGO\",\"OPUL\",...],\"sort\":\"rank\",\"order\":\"ascending\",\"offset\":0,\"limit\":0,\"meta\":false}");
        writer.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null) {
            builder.append(line).append("\n");
        }
        System.out.println("builder = " + builder);
        return new JSONArray(builder.toString());
    }
    static class Swap {
        public String code_a;
        public String code_b;
        public double sum_a;
        public double sum_b;
        public double rate;
        public Swap(String code_a, String code_b, double sum_a, double sum_b) {
            this.code_a = code_a;
            this.code_b = code_b;
            this.sum_a = sum_a;
            this.sum_b = sum_b;
            rate = sum_a / sum_b;
        }
    }
    public static double getDbl(JSONObject o, String k) {
        if (!o.has(k) || o.isNull(k)) {
            return -1;
        }
        return o.getDouble(k);
    }
    public static void update() throws IOException {
        orders = new ArrayList<>();
        if (new File("my_algo_view.txt").canRead()) {
            BufferedReader reader = new BufferedReader(new FileReader("my_algo_view.txt"));
            String l;
            while ((l = reader.readLine()) != null) {
                String[] sa = l.split(";");
                orders.add(new Swap(sa[0], sa[1], Double.parseDouble(sa[2]), Double.parseDouble(sa[3])));
            }
            reader.close();
        }
        date = new Date();
        JSONArray a = getJsonArray_a();
        rows = new ArrayList<>();
        for (int i = 0; i < a.length(); i++) {
            JSONObject o1 = a.getJSONObject(i);
            JSONObject o2 = o1.getJSONObject("delta");
            ArrayList<Comparable> r = new ArrayList<>();
            r.add(o1.getString("code"));
            r.add(o1.getDouble("rate"));
            Swap s = null;
            for (Swap swap : orders) {
                if (swap.code_b.equalsIgnoreCase(o1.getString("code"))) {
                    s = swap;
                }
            }
            if (s != null) {
                r.add((float) (o1.getDouble("rate") / s.rate * 100.0));
            } else {
                r.add(-1f);
            }
            r.add(getDbl(o2, "hour"));
            r.add(getDbl(o2, "day"));
            r.add(getDbl(o2, "week"));
            r.add(getDbl(o2, "month"));
            r.add(getDbl(o2, "quarter"));
            r.add(getDbl(o2, "year"));
            rows.add(r);
        }
    }
    public static void show() {
        System.out.println(date);
        System.out.println(AsciiTable.getTable(rows, Arrays.asList(
                new Column().header("Code").with(o1 -> o1.get(0).toString()),
                new Column().header("Rate").with(o1 -> ((Float) ((Double) o1.get(1)).floatValue()).toString()),
                new Column().header("%").with(o1 -> o1.get(2).toString()),
                new Column().header("h").with(o1 -> o1.get(3).toString()),
                new Column().header("d").with(o1 -> o1.get(4).toString()),
                new Column().header("w").with(o1 -> o1.get(5).toString()),
                new Column().header("mon").with(o1 -> o1.get(6).toString()),
                new Column().header("qua").with(o1 -> o1.get(7).toString()),
                new Column().header("year").with(o1 -> o1.get(8).toString())
        )));
    }
    public static void main(String[] args) throws IOException {
        while (true) {
            System.out.println("Options: 1:show 2:update 3:sort_by 4:add_swap");
            int o = new Scanner(System.in).nextInt();
            if (o == 1) {
                if (rows == null) {
                    update();
                }
                show();
            } else if (o == 2) {
                update();
                show();
            } else if (o == 3) {
                int c = new Scanner(System.in).nextInt() - 1;
                rows.sort(Comparator.comparing(o1 -> o1.get(c)));
                show();
            } else if (o == 4) {
                System.out.println("String code_a, String code_b, double sum_a, double sum_b");
                String[] sa = new Scanner(System.in).nextLine().split(" ");
                orders.add(new Swap(sa[0], sa[1], Double.parseDouble(sa[2]), Double.parseDouble(sa[3])));
                PrintWriter writer = new PrintWriter("my_algo_view.txt");
                for (Swap s : orders) {
                    writer.println(s.code_a + ";" + s.code_b + ";" + s.sum_a + ";" + s.sum_b);
                }
                writer.close();
                show();
            } else {
                break;
            }
        }
    }
}