<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %} AIND Data Transfer Service</title>
    <style>
    body {
        margin: 20px;
        font-family: arial, sans-serif;
    }
    fieldset {
      display:inline
    }
    table {
      border-collapse: collapse;
      width: 75%;
    }
    td, th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
    }
    th, tr:hover {
        background-color: #E8EAF6;
        color: #3F51B5;
    }
    #submit { 
        border: none;
        border-radius: 6px;
        color: #ffffff;
        padding: 8px;
        width: 80px;
        font-size: medium;
        background-color: #5065df;
        &:hover { background-color: #3f51b5; }
    }
    #message {
        margin-top: 20px;
        &.success { color: green; }
        &.error { color: red; }
    }
    </style>
</head>
<body>
    <nav>
        <a href="/">Submit Jobs</a> |
        <a href="/jobs">Job Status</a> |
        <a href="/job_params">Job Parameters</a> |
        <a title="Download job template as .xslx" href= "/api/job_upload_template" download>Job Submit Template</a> |
        <a title="List of project names" href= "{{ project_names_url }}" target="_blank" >Project Names</a> |
        <a title="For more information click here" href="https://aind-data-transfer-service.readthedocs.io"  target="_blank" >Help</a>
    </nav>
    <br>
    <div>
        <p1>For instructions on how to submit jobs click on the Help tab</p1>
    </div>
    <h2>Submit Jobs</h2>
        <div>
        <fieldset>
            <legend>Mail Notifications (optional)</legend><br>
            <div>
                <label for="email" title="Optionally provide an allen institute email address to receive upload job status notifications">Allen Institute email:</label>
                <input type="email" id="email" pattern=".+@alleninstitute\.org" size="30" placeholder="@alleninstitute.org" /><br><br>
            </div>
            <div>
                <input type="checkbox" id="begin" name="begin" />
                <label for="begin">BEGIN</label> |
                <input type="checkbox" id="end" name="end" />
                <label for="end">END</label> |
                <input type="checkbox" id="fail" name="fail" checked />
                <label for="fail">FAIL</label> |
                <input type="checkbox" id="retry" name="retry" />
                <label for="retry">RETRY</label> |
                <input type="checkbox" id="all" name="all" />
                <label for="all">ALL</label>
            </div>
        </fieldset>
        </div><br><br>
    <form id="file_form" method="post" enctype="multipart/form-data">
        <label for="file">Please select a .csv or .xlsx file:</label>
        <input type="file" id="file" name="file" accept=".csv,.xlsx" onchange="validateJobs(this)" onclick="this.value=null"><br><br>
    </form>
    <button id="submit" type="button" onclick="submitJobs()">Submit</button>
    <div id="message"></div><br>
    <div id="response"></div>
    <script>
        var jobs = []
        var parsing_errors = []
        const msgTypes = {
            "validatePending": "Validating...",
            "validateSuccess": "Successfully validated jobs from file.",
            "validateError": "Error validating jobs from file.",
            "submitPending": "Submitting jobs. Please do not refresh or re-submit...",
            "submitSuccess": "Successfully submitted jobs.",
            "submitError": "Error submitting jobs."
        }
        setMessage = function(msgType) {
            $("#message").removeClass("success");
            $("#message").removeClass("error");
            $("#message").html(msgType);
            if (msgType == msgTypes.validateSuccess || msgType == msgTypes.submitSuccess) {
                $("#message").addClass("success");
            } else if (msgType == msgTypes.validateError || msgType == msgTypes.submitError) {
                $("#message").addClass("error");
            }
        };
        addTableRow = function(data, table, tr, td, isHeader) {
            tr = document.createElement('tr');
            for (var d of data) {
                td = document.createElement(isHeader ? 'th' : 'td');
                td.innerHTML = d.value ?? d;
                if (d.rowspan) {
                    td.setAttribute("rowspan", d.rowspan);
                }
                tr.append(td);
            }
            table.appendChild(tr);
        };
        validateJobs = function(fileElement) {
            if (fileElement.files.length != 1) {
                // File attach was cancelled by user
                return;
            } 
            if (![".csv", ".xlsx"].some(ext => fileElement.files[0].name.endsWith(ext))) {
                fileElement.value = null;
                alert("Invalid file type. Please attach a .csv or .xlsx file.");
                return;
            }
            var formData = new FormData(document.getElementById("file_form"));
            $.ajax({
                url: "/api/v2/validate_csv",
                type: "POST",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function() {
                    setMessage(msgTypes.validatePending);
                    $("#response").html("");
                },
                success: function(data) {
                    setMessage(msgTypes.validateSuccess);
                    jobs = data["data"]["jobs"];
                    parsing_errors = []
                    let jobsLength = jobs.length;
                    var table = document.createElement('table'), tr, td, row;
                    addTableRow(
                        [ "job_type", "project_name", "s3_bucket", "platform", "subject_id", "acq_datetime", "metadata_dir", "modality", "modality.input_source" ],
                        table, tr, td, true
                    );
                    for (row = 0; row < jobsLength; row++) {
                        let job = jobs[row];
                        let modalities = job.tasks?.modality_transformation_settings;
                        if (modalities) {
                            modalities = Object.entries(modalities).map(([key, value]) => ({
                                abbreviation: key,
                                input_source: value.job_settings?.input_source
                            }))
                        }
                        let modalitiesLength = modalities ? modalities.length: 0;
                        let metadata_dir = job.tasks?.gather_preliminary_metadata?.job_settings?.metadata_dir
                        addTableRow(
                            [
                                { value: job.job_type,                 rowspan: modalitiesLength },
                                { value: job.project_name,             rowspan: modalitiesLength },
                                { value: job.s3_bucket,                rowspan: modalitiesLength },
                                { value: job.platform.abbreviation,    rowspan: modalitiesLength },
                                { value: job.subject_id,               rowspan: modalitiesLength },
                                { value: job.acq_datetime,             rowspan: modalitiesLength },
                                { value: metadata_dir ?? "",           rowspan: modalitiesLength },
                                modalities ? modalities[0].abbreviation : "",
                                modalities ? modalities[0].input_source : ""
                            ], table, tr, td, false
                        );
                        for (mRow = 1; mRow < modalitiesLength; mRow++) {
                            let modality = modalities[mRow]
                            addTableRow(
                                [ modality.abbreviation, modality.input_source ],
                                table, tr, td, false
                            );
                        }
                    }
                    $("#response").html(table);
                },
                error: function(data) {
                    jobs = []
                    parsing_errors = data.responseJSON["data"]["errors"]
                    setMessage(msgTypes.validateError);
                    $("#response").html(parsing_errors.map((err) => {
                        return `<li>${err}</li>`
                    }));
                }
            });
        };
        submitJobs = function() {
            if(jobs.length > 0 && parsing_errors.length == 0){
                let job_settings = {};
                let mail_user = $("#email").val();
                if (mail_user !== "" && mail_user !== undefined) {
                    job_settings["user_email"] = mail_user;
                };
                let mail_type = [];
                if ($("#all").is(":checked")) {
                    mail_type = ["all"];
                };
                if ($("#begin").is(":checked")) {
                    mail_type.push("begin");
                };
                if ($("#end").is(":checked")) {
                    mail_type.push("end");
                };
                if ($("#fail").is(":checked")) {
                    mail_type.push("fail");
                };
                if ($("#retry").is(":checked")) {
                    mail_type.push("retry");
                };
                job_settings["email_notification_types"] = mail_type
                job_settings["upload_jobs"] = jobs
                $.ajax({
                    url: "/api/v2/submit_jobs",
                    type: "POST",
                    data: JSON.stringify(job_settings),
                    contentType: 'application/json; charset=utf-8',
                    beforeSend: function() {
                        setMessage(msgTypes.submitPending);
                        $("#response").html("");
                    },
                    success: function (data) {
                        jobs = []
                        parsing_errors = []
                        setMessage(msgTypes.submitSuccess);
                        $("#response").html(data);
                    },
                    error: function(data) {
                        jobs = []
                        setMessage(msgTypes.submitError);
                        let errors = data.responseJSON["data"]["errors"];
                        try {
                            parsing_errors = JSON.parse(errors).map((err) => JSON.stringify(err));
                        } catch (e) {
                            parsing_errors = (typeof errors == "string") ? [errors] : errors;
                        }
                        $("#response").html(parsing_errors.map((errStr) => {
                            return `<li>${errStr}</li>`
                        }));
                    }
                });
            } else if (jobs.length == 0) {
                alert("No valid jobs to submit. Please attach a .csv or .xlsx file with valid jobs.");
                return;
            }
        };
    </script>
</body>
</html>
