import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

/**
 * This example demonstrates how to email a file using the server REST API.
 */
public class EmailFileExample {

    private static final BufferedReader CONSOLE_READER = new BufferedReader(new InputStreamReader(System.in));

    private static final String LOGIN_URL_TEMPLATE = "http://%s:%s/rest/login";
    private static final String LOGOUT_URL_TEMPLATE = "http://%s:%s/rest/logout";
    private static final String EMAIL_URL_TEMPLATE = "http://%s:%s/rest/files/email";

    private static final String LOGIN_TEMPLATE = "{\"domain\":\"%s\",\"username\":\"%s\", \"password\":\"%s\"}";
    private static final String DETAILS_TEMPLATE =
            "{\"files\":[\"%s\"],"
            + "\"sender\":\"%s\","
            + "\"recipients\":[\"%s\"],"
            + "\"subject\":\"Test file\","
            + "\"message\":\"This is a test file.\","
            + "\"password\":\"secret\","
            + "\"generateRandomPassword\":false,"
            + "\"expireAfterDays\":1,"
            + "\"maxDownloads\":1,"
            + "\"deleteAfterMaxDownloads\":true,"
            + "\"secure\":false}";

    private static final String CHARSET = "UTF-8";

    private final String host;
    private final int port;
    private final String username;
    private final String password;
    private final String domainName;
    private final String filePath;
    private final String sender;
    private final String recipient;
    private String sessionId;

    /**
     * The application entry point.
     *
     * @param arguments command line arguments
     * @throws Exception if an error occurs
     */
    public static void main(String[] arguments)
            throws Exception {
        showExampleTitle();
        EmailFileExample example = createExample();
        example.execute();
    }

    /**
     * Shows example title.
     */
    private static void showExampleTitle() {
        System.out.println("This example demonstrates how to email a file using the server REST API.");
        System.out.println();
    }

    /**
     * Creates an example instance.
     *
     * @return an example instance
     * @throws Exception if an error occurs
     */
    private static EmailFileExample createExample()
            throws Exception {
        String host = getParameter("Enter server HTTP/S host: ");
        int port = Integer.parseInt(getParameter("Enter server HTTP/S port: "));
        String username = getParameter("Enter username: ");
        String password = getParameter("Enter password: ");
        String domainName = getParameter("Enter domain name: ");
        String path = getParameter("Enter file path: ");
        String sender = getParameter("Enter sender email: ");
        String recipient = getParameter("Enter recipient email: ");

        return new EmailFileExample(host, port, username, password, domainName, path, sender, recipient);
    }

    /**
     * Support method. Shows prompt on console and reads user response.
     *
     * @param prompt prompt string
     * @return user response
     * @throws Exception if an I/O error occurs
     */
    private static String getParameter(String prompt)
            throws Exception {
        System.out.print(prompt);
        return CONSOLE_READER.readLine();
    }

    /**
     * Constructs example.
     *
     * @param host server REST host
     * @param port server REST port
     * @param username server username
     * @param password server password
     * @param domainName domain name
     * @param filePath file to send
     * @param sender the email sender address
     * @param recipient the email recipient address
     */
    public EmailFileExample(String host,
                            int port,
                            String username,
                            String password,
                            String domainName,
                            String filePath,
                            String sender,
                            String recipient) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.domainName = domainName;
        this.filePath = filePath;
        this.sender = sender;
        this.recipient = recipient;
    }

    /**
     * Starts domain.
     */
    public void execute() {
        try {
            login();

            String fileDetailsString = createFileDetailsString();
            emailFile(fileDetailsString);

            logout();

            System.out.println("File emailed successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Performs server login.
     *
     * @throws Exception if an error occurs
     */
    private void login()
            throws Exception {
        URL url = new URL(String.format(LOGIN_URL_TEMPLATE, this.host, this.port));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            String authenticationString = String.format(LOGIN_TEMPLATE, this.domainName, this.username, this.password);
            byte[] authenticationData = authenticationString.getBytes(CHARSET);

            connection.setRequestProperty("Content-Length", Integer.toString(authenticationData.length));

            OutputStream out = connection.getOutputStream();
            out.write(authenticationData);
            out.close();

            assertRequestSucceeded(connection);

            String cookie = connection.getHeaderField("Set-Cookie");
            this.sessionId = new Scanner(cookie).useDelimiter(";").next();
        } finally {
            connection.disconnect();
        }
    }

    /**
     * Emails the file.
     *
     * @param fileDetailsString the file details string
     *
     * @throws Exception if an error occurs
     */
    private void emailFile(String fileDetailsString)
            throws Exception {
        URL url = new URL(String.format(EMAIL_URL_TEMPLATE, this.host, this.port));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Cookie", this.sessionId);
            connection.setRequestProperty("Content-Type", "application/json");

            byte[] detailsData = fileDetailsString.getBytes(CHARSET);

            connection.setRequestProperty("Content-Length", Integer.toString(detailsData.length));

            OutputStream out = connection.getOutputStream();
            out.write(detailsData);
            out.close();

            assertRequestSucceeded(connection);
        } finally {
            connection.disconnect();
        }
    }

    /**
     * Performs server logout.
     *
     * @throws Exception if an error occurs
     */
    private void logout()
            throws Exception {
        URL url = new URL(String.format(LOGOUT_URL_TEMPLATE, this.host, this.port));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Cookie", this.sessionId);
        } finally {
            connection.disconnect();
        }
    }

    /**
     * Asserts that request was successful.
     *
     * @param connection target connection
     *
     * @throws Exception if an error occurs
     */
    private void assertRequestSucceeded(HttpURLConnection connection)
            throws Exception {
        if (connection.getResponseCode() > 299) {
            throw new Exception(String.format("HTTP request error. Response code: %d", connection.getResponseCode()));
        }
    }

    /**
     * Creates a details string.
     *
     * @return a details string
     */
    private String createFileDetailsString() {
        return String.format(DETAILS_TEMPLATE, this.filePath, this.sender, this.recipient);
    }
}
