import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import static java.lang.System.exit;


public class ReplaceDocumentTutorial {

    // Replace with your HostMyApi Data Table URL
    private static String HOST_MY_API_TABLE_URL;
    // Replace with your HostMyApi Access Key
    private static String HOST_MY_API_KEY_ID;


    public static void main(String[] args) {
        System.out.println("Current directory: " + System.getProperty("user.dir"));

        System.out.println("Arguments Passed: " + args.length);
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + i + " is: " + args[i]);
        }
        if (args.length < 2) {
            System.out.println();
            System.out.println("Error: " + "Must provide 2 arguments for TABLE URL and Key ID.");
            exit(-1);
        } else {

            HOST_MY_API_TABLE_URL = args[0];
            HOST_MY_API_KEY_ID = args[1];
            System.out.println();
            System.out.println("Information: " + "TABLE URL used is " + HOST_MY_API_TABLE_URL);
            System.out.println("Information: " + "KEY ID used is " + HOST_MY_API_KEY_ID);
            System.out.println();

            try {
                var url = URI.create(HOST_MY_API_TABLE_URL).toURL();
                HttpURLConnection connectionDelete = (HttpURLConnection) url.openConnection();
                // Set Header with the HostMyApi Access Key
                connectionDelete.setRequestProperty("X-API-KEY", HOST_MY_API_KEY_ID);
                // Delete the old Document
                connectionDelete.setRequestMethod("DELETE");
                int responseCodeDelete = connectionDelete.getResponseCode();
                if (responseCodeDelete == HttpURLConnection.HTTP_OK) { // success
                    // Old Document Delete has succeeded, now create new document

                    // Set POST request
                    HttpURLConnection connectionPost = (HttpURLConnection) url.openConnection();
                    // Set Header with the HostMyApi Access Key
                    connectionPost.setRequestProperty("X-API-KEY", HOST_MY_API_KEY_ID);
                    connectionPost.setRequestMethod("POST");
                    connectionPost.setRequestProperty("Accept", "application/json");
                    connectionPost.setRequestProperty("Content-Type", "application/json");
                    connectionPost.setDoOutput(true);
                    OutputStream os = connectionPost.getOutputStream();
                    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                    File daysOfWeekV01 = new File("Weekdays_en_de_v01.json");
                    Scanner myReader = new Scanner(daysOfWeekV01);
                    while (myReader.hasNextLine()) {
                        String dayOfWeek = myReader.nextLine();
                        osw.write(dayOfWeek);
                    }
                    osw.flush();
                    osw.close();
                    os.close();  //don't forget to close the OutputStream

                    int responseCodePost = connectionPost.getResponseCode();
                    if (responseCodePost == HttpURLConnection.HTTP_OK) { // success
                        BufferedReader in = new BufferedReader(new InputStreamReader(connectionPost.getInputStream(), StandardCharsets.UTF_8));
                        String inputLine;
                        while ((inputLine = in.readLine()) != null) {
                            System.out.println(inputLine);
                        }
                        in.close();
                        connectionPost.disconnect();
                    } else {
                        System.out.println("HostMyApi Data request has not worked");
                        System.out.println("status: " + responseCodePost);
                        System.out.println("error: \"" + "\"");
                        System.out.println("message: \"" + "\"");
                        System.out.println("path: \"" + url.getPath() + "\"");
                        System.out.println();
                        /**
                         * Try to emulate Curl error response:
                         * timestamp: 1723546524584
                         * status: 400
                         * error: "Bad Request"
                         * message: "You must provide an api key for this request" from HTTP Status Message
                         * path: "/v2/tables/T-c4b024cf-ad56-4b93-a4c7-ccfa501c3929"
                         */
                        System.out.println("POST request has not worked");
                        BufferedReader errorReader = new BufferedReader(new InputStreamReader(connectionPost.getErrorStream(), StandardCharsets.UTF_8));
                        String errorLine;
                        StringBuilder errorContent = new StringBuilder();
                        while ((errorLine = errorReader.readLine()) != null) {
                            errorContent.append(errorLine);
                            System.out.println(errorLine);
                        }
                        errorReader.close();
                        System.out.println("Error Response: " + errorContent.toString());


                        Map<String, List<String>> map = connectionPost.getHeaderFields();
                        System.out.println("Printing All Response Header for URL: " + HOST_MY_API_TABLE_URL + "\n");
                        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                            System.out.println(entry.getKey() + " : " + entry.getValue());
                        }

                    }
                } else {
                    // Old Document Delete failed
                    System.out.println("HostMyApi Data request has not worked");
                    System.out.println("status: " + responseCodeDelete);
                    System.out.println("error: \"" + "\"");
                    System.out.println("message: \"" + "\"");
                    System.out.println("path: \"" + url.getPath() + "\"");
                    System.out.println();
                    /**
                     * Try to emulate Curl error response:
                     * timestamp: 1723546524584
                     * status: 400
                     * error: "Bad Request"
                     * message: "You must provide an api key for this request" from HTTP Status Message
                     * path: "/v2/tables/T-c4b024cf-ad56-4b93-a4c7-ccfa501c3929"
                     */
                    System.out.println("DELETE request has not worked");
                    BufferedReader errorReader = new BufferedReader(new InputStreamReader(connectionDelete.getErrorStream(), StandardCharsets.UTF_8));
                    String errorLine;
                    StringBuilder errorContent = new StringBuilder();
                    while ((errorLine = errorReader.readLine()) != null) {
                        errorContent.append(errorLine);
                        System.out.println(errorLine);
                    }
                    errorReader.close();
                    System.out.println("Error Response: " + errorContent.toString());


                    Map<String, List<String>> map = connectionDelete.getHeaderFields();
                    System.out.println("Printing All Response Header for URL: " + HOST_MY_API_TABLE_URL + "\n");
                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        System.out.println(entry.getKey() + " : " + entry.getValue());
                    }


                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}