package demo;

import com.elixirtech.RepertoireClient;
import com.elixirtech.ers2.client.ERSClient;
import com.elixirtech.ers2.client.JobInfo;
import com.elixirtech.report2.runtime.IJobInfo;

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;

/**
 * A series of example implementations of the repertoire client
 */
public class JavaDemo {
    final static String server = "http://localhost:1740";
    final static String username = "admin";
    final static String password = "sa";

    public static void main(String[] args) throws IOException {
        loggingInit();
        testDS1();
        testOldDS();
        testRml1();
        testRmlWithParam();
        testRml2();
        testOldRml();
        testDocX1();
        testDocXWithParam();
        testOldDocX();
        //testDocX2();
        //testDSWithAPIToken();
    }

    /**
     * Sets up the logging levels for the following examples
     */
    private static void loggingInit() {
        Logger logger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
        if (logger != null) {
            logger.setLevel(Level.INFO);
            Logger orgLogger = (Logger) LoggerFactory.getLogger("org");
            if (orgLogger != null ) {
                orgLogger.setLevel(Level.WARN);
            }
        }
    }

    /**
     * An example reading a DS file from the server using the new RepertoireClient with a username and password
     */
    private static void testDS1() {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        JobInfo info = client.generateData("/ElixirSamples/DataSource/FruitSales.ds", new java.util.HashMap<String, String>(), os);
        System.out.println(new String(os.toByteArray(),StandardCharsets.UTF_8));
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }


    /**
     * An example reading a DS file from the server using the old ERSClient format
     * @throws IOException
     */
    private static void testOldDS() throws IOException {
        ERSClient client = new ERSClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        client.generateData("/ElixirSamples/DataSource/FruitSales.ds", os, new java.util.Properties());
        System.out.println(new String(os.toByteArray(),StandardCharsets.UTF_8));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders an RML file from the server to a local folder as a PDF using the new RepertoireClient
     * @throws IOException
     */
    private static void testRml1() throws IOException {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HashMap<String, String> emptyMap = new HashMap<>();
        JobInfo info = client.renderReport("/ElixirSamples/Report/RML/Master-Detail Report.rml", "application/pdf", emptyMap, emptyMap, os);
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "sample-rml1.pdf");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders an RML file from the server to a local folder as a PDF using the new RepertoireClient and passing a parameter to the renderer
     * @throws IOException
     */
    private static void testRmlWithParam() throws IOException {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("Staff Name", "John Doe");
        HashMap<String, String> emptyMap = new HashMap<>();
        JobInfo info = client.renderReport("/ElixirSamples/Report/RML/Pivot Table.rml", "application/pdf", paramMap, emptyMap, os);
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "sample-rmlParam.pdf");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders an RML file from the server to a local folder as an XLSX using the new RepertoireClient
     * @throws IOException
     */
    private static void testRml2() throws IOException {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HashMap <String, String> emptyMap = new java.util.HashMap<>();
        JobInfo info = client.renderReport("/ElixirSamples/Report/RML/Master-Detail Report.rml", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", emptyMap, emptyMap, os);
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "sample-rml1.xlsx");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders an RML file from the server to a local folder as an XLSX using the old ERSClient
     * @throws IOException
     */
    private static void testOldRml() throws IOException {
        ERSClient client = new ERSClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IJobInfo info = client.renderReport(
                "/ElixirSamples/Report/RML/Master-Detail Report.rml",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                os,
                new java.util.Properties()
        );
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "OldStyleSampleRml1.xlsx");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println("status-code: " + info.getInteger("status-code"));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders a DocX from the server to a local folder as a DocX using the new RepertoireClient
     * @throws IOException
     */
    private static void testDocX1() throws IOException {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HashMap<String, String> emptyMap = new HashMap<>();
        JobInfo info = client.renderDocX(
                "/ElixirSamples/Report/DocX/Customer Profile by Location.docx",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                emptyMap,
                os
        );
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "SampleDocX.docx");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders a DocX from the server to a local folder using the new RepertoireClient and passing a parameter to the renderer
     * @throws IOException
     */
    private static void testDocXWithParam() throws IOException {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("city", "Cliffside");
        JobInfo info = client.renderDocX(
                "/ElixirSamples/Report/DocX/Customer Profile by Location.docx",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                paramMap,
                os
        );
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "SampleDocXParam.docx");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders a DocX from the server to a local folder as a DocX using the old ERSClient
     * @throws IOException
     */
    private static void testOldDocX() throws IOException {
        ERSClient client = new ERSClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IJobInfo info = client.renderDocX(
                "/ElixirSamples/Report/DocX/Customer Profile by Location.docx",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                os,
                new java.util.Properties()
        );
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "OldStyleSampleDocX.docx");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println("(status-code:" + info.getInteger(IJobInfo.STATUS_CODE) + ", elapsed-time:" +
                info.getLong(IJobInfo.ELAPSED_TIME) + ", byte-size: " + info.getLong(IJobInfo.BYTE_SIZE) + ")");
        System.out.println("-------------------------------------------");
    }

    /**
     * An example that renders a DocX from the server to a local folder as a PDF using the new RepertoireClient
     *
     * Initially commented out as it requires a separate aspose licence
     * @throws IOException
     */
    /*private static void testDocX2() throws IOException {
        RepertoireClient client = new RepertoireClient(server, username, password);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        HashMap<String, String> emptyMap = new HashMap<>();
        JobInfo info = client.renderDocX("/ElixirSamples/Report/DocX/Customer Profile by Location.docx", "application/pdf", emptyMap, os);
        File tmpDir = new File(System.getProperty("java.io.tmpdir"));
        File output = new File(tmpDir, "SampleDocX.pdf");
        Files.write(output.toPath(), os.toByteArray());
        System.out.println("File rendered to: " + output.getAbsolutePath());
        System.out.println(info.getEntries().mkString("Entries(", ", ", ")"));
        System.out.println("-------------------------------------------");
    }*/


    /**
     * An example reading a DS file from the server using the new RepertoireClient with an API token
     *
     * This function is initially commented out as it uses API token authentication
     */
    /*private static void testDSWithAPIToken() {
        String apiToken = "c532b968-fd1e-4b02-b065-48b122def059"; //Insert your token here
        RepertoireClient client = new RepertoireClient(server, apiToken);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        client.generateData("/ElixirSamples/DataSource/FruitSales.ds", new java.util.HashMap<String, String>(), os);
        System.out.println(new String(os.toByteArray(),StandardCharsets.UTF_8));
        System.out.println("-------------------------------------------");
    }*/
}
