<window id="batchDetails">
    <layout type="vertical">
        <layout type="horizontal">
            <button type="push" id="target" name="Load profile as target" />
            <button type="push" id="compare" name="Compare profile" />
            <stretch />
            <label>Search:</label>
            <line id="search" />
        </layout>
        <tabbar id="tabs" />
        <layout type="stack" id="pages">
            <page>
                <layout type="vertical">
                    <webview id="view" />
                </layout>
            </page>
            <page>
                <layout type="vertical">
                    <splitter type="horizontal" id="logsplit">
                        <measurementtable id="log">
                            <column>Time</column>
                            <column>Bean</column>
                            <column>Air</column>
                            <column>Note</column>
                        </measurementtable>
                        <graph id="graph" />
                    </splitter>
                </layout>
            </page>
            <page>
                <layout type="vertical">
                    <layout type="horizontal">
                        <label>Roasted Weight: </label>
                        <line id="roasted" validator="numeric" />
                        <line id="roastunit" writable="false" />
                        <stretch />
                    </layout>
                    <label>Degree of Roast</label>
                    <layout type="horizontal">
                        <label>Whole Bean:</label>
                        <roastcoloredit id="wholecolor" />
                        <stretch />
                    </layout>
                    <label id="wholespec">-</label>
                    <layout type="horizontal">
                        <label>Ground:</label>
                        <roastcoloredit id="groundcolor" />
                        <stretch />
                    </layout>
                    <label id="groundspec">-</label>
                    <button type="check" name="Approved" id="approval" />
                    <layout type="horizontal">
                        <label>Annotation</label>
                        <textarea id="annotation" />
                    </layout>
                    <button type="push" id="submit" name="Save" />
                    <stretch />
                </layout>
            </page>
            <page>
                <layout type="vertical">
                    <webview id="batchTag" />
                    <layout type="horizontal">
                        <printerselector id="printerlist" />
                        <button name="Print" id="printbutton" type="push" />
                    </layout>
                </layout>
            </page>
        </layout>
    </layout>
    <menu name="File">
        <item id="save" shortcut="Ctrl+S">Save Profile...</item>
        <item id="print" shortcut="Ctrl+P">Print Report...</item>
    </menu>
    <menu name="Log">
        <item id="showC">Display Celsius</item>
        <item id="showF">Display Fahrenheit</item>
        <separator />
        <item id="ms">Millisecond View</item>
        <item id="1s">1 Second View</item>
        <item id="5s">5 Second View</item>
        <item id="10s">10 Second View</item>
        <item id="15s">15 Second View</item>
        <item id="30s">30 Second View</item>
        <item id="1m">1 Minute View</item>
    </menu>
    <program>
        <![CDATA[
            var window = this;
            var tabs = findChildObject(this, 'tabs');
            tabs.addTab("Report");
            tabs.addTab("Profile");
            tabs.addTab("Edit");
            tabs.addTab("Batch Tag");
            var pages = findChildObject(this, 'pages');
            tabs.currentChanged.connect(function(index) {
                pages.setCurrentIndex(index);
            });
            var log = findChildObject(this, 'log');
            var graph = findChildObject(this, 'graph');
            var showC = findChildObject(this, 'showC');
            showC.triggered.connect(function() {
                log.setDisplayUnits(Units.Celsius);
                graph.showC();
            });
            var showF = findChildObject(this, 'showF');
            showF.triggered.connect(function() {
                log.setDisplayUnits(Units.Fahrenheit);
                graph.showF();
            });
            var v1 = findChildObject(this, 'ms');
            v1.triggered.connect(log.LOD_ms);
            var v2 = findChildObject(this, '1s');
            v2.triggered.connect(log.LOD_1s);
            var v3 = findChildObject(this, '5s');
            v3.triggered.connect(log.LOD_5s);
            var v4 = findChildObject(this, '10s');
            v4.triggered.connect(log.LOD_10s);
            var v5 = findChildObject(this, '15s');
            v5.triggered.connect(log.LOD_15s);
            var v6 = findChildObject(this, '30s');
            v6.triggered.connect(log.LOD_30s);
            var v7 = findChildObject(this, '1m');
            v7.triggered.connect(log.LOD_1m);
            var splitter = findChildObject(this, 'logsplit');
            splitter.restoreState("script/offlineViewSplitter");
            window.saveTemperatureColumns = new Array();
            window.saveAnnotationColumns = new Array();
            this.aboutToClose.connect(function() {
                splitter.saveState("script/batchdetails/profileSplitter");
            });
            var unit = QSettings.value("script/history_unit", 1);
            var conversion = 1;
            if(unit == 0)
            {
                conversion = 2.2;
            }
            var unitText = (unit == 0 ? TTR("batchDetails", "Kg") :
                           TTR("batchDetails", "Lb"));
            dataView = findChildObject(this, 'view');
            var printMenu = findChildObject(this, 'print');
            printMenu.triggered.connect(function() {
                dataView.print();
            });
            var fileID;
            var target = findChildObject(this, 'target');
            var compare = findChildObject(this, 'compare');
            if(typeof(Windows.loggingWindow) == "undefined") {
                compare.enabled = false;
                target.enabled = false;
            }
            var tableReference;
            var rowReference;
            var batchTime;
            var machine;
            var approval;
            var annotation;
            var roastWeight;
            compare.clicked.connect(function() {
                var query = new QSqlQuery;
                query.prepare("SELECT file, name FROM files WHERE id = :id");
                query.bind(":id", Number(fileID));
                query.exec();
                query.next();
                var buffer = new QBuffer(query.value(0));
                var pname = query.value(1);
                query = query.invalidate();
                var startSeries = Number(QSettings.value('cseries', 3));
                var nextSeries = startSeries + 2;
                QSettings.setValue('cseries', nextSeries);
                var input = new XMLInput(buffer, startSeries);
                var graph = findChildObject(Windows.loggingWindow, 'graph');
                input.measure.connect(graph.newMeasurement);
                input.input();
                query = query.invalidate();
            });
            target.clicked.connect(function() {
                var query = new QSqlQuery;
                query.prepare("SELECT file, name FROM files WHERE id = :id");
                query.bind(":id", Number(fileID));
                query.exec();
                query.next();
                var buffer = new QBuffer(query.value(0));
                var pname = query.value(1);
                query = query.invalidate();
                var input = new XMLInput(buffer, 1);
                var graph = findChildObject(Windows.loggingWindow, 'graph');
                var log = findChildObject(Windows.loggingWindow, 'log');
                log.clear();
                graph.clear();
                input.newTemperatureColumn.connect(log.setHeaderData);
                input.newTemperatureColumn.connect(function(col, text) {
                    if(text == Windows.loggingWindow.targetcolumnname) {
                        targetseries = col;
                    }
                });
                input.newAnnotationColumn.connect(log.setHeaderData);
                input.measure.connect(graph.newMeasurement);
                input.measure.connect(log.newMeasurement);
                input.measure.connect(function(data, series) {
                    if(series == targetseries) {
                        targetDetector.newMeasurement(data);
                    }
                });
                var lc;
                input.lastColumn.connect(function(c) {
                    lc = c;
                    QSettings.setValue("liveColumn", c + 1);
                    Windows.loggingWindow.postLoadColumnSetup(c);
                });
                input.annotation.connect(log.newAnnotation);
                input.annotation.connect(function(note, tcol, ncol) {
                    for(var i = tcol; i < ncol; i++) {
                        log.newAnnotation(note, i, ncol);
                    }
                });
                Windows.loggingWindow.windowTitle = "Typica - " + pname;
                Windows.loggingWindow.raise();
                Windows.loggingWindow.activateWindow();
                input.input();
                log.newAnnotation(TTR("batchDetails", "End"), 1, lc);
                query = query.invalidate();
            });
            var approvalButton = findChildObject(this, 'approval');
            var annotationField = findChildObject(this, 'annotation');
            var roastedEdit = findChildObject(this, 'roasted');
            var unitEdit = findChildObject(this, 'roastunit');
            var wholecolor = findChildObject(this, 'wholecolor');
            var groundcolor = findChildObject(this, 'groundcolor');
            window.loadBatch = function(mref, tref) {
                machine = mref;
                batchTime = tref;
                var query = new QSqlQuery();
                var q = "WITH names AS ( WITH greens AS ( SELECT unnest(unroasted_id) AS gitem, machine, time FROM roasting_log WHERE machine = :machine AND time = :time) SELECT array_agg((SELECT name FROM items WHERE id = greens.gitem) || ' (' || gitem || ')') AS names, max(greens.machine) AS machine, max(greens.time) AS time FROM greens LIMIT 1) SELECT (SELECT name FROM items WHERE id = roasted_id), duration, names, unroasted_quantity, (unroasted_total_quantity/:c1)::numeric(12,3), (roasted_quantity/:c2)::numeric(12,3), approval, files, annotation, (SELECT file FROM files WHERE id = files[1]) AS file, additional_data, roasted_id FROM names, roasting_log WHERE roasting_log.machine = names.machine AND roasting_log.time = names.time";
                query.prepare(q);
                query.bind(":machine", mref);
                query.bind(":time", tref);
                query.bind(":c1", conversion);
                query.bind(":c2", conversion);
                query.exec();
                query.next();
                var buffer = new QBuffer;
                buffer.open(3);
                var output = new XmlWriter(buffer);
                output.writeStartDocument("1.0");
                output.writeDTD('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg.dtd">');
                output.writeStartElement("html");
                output.writeAttribute("xmlns", "http://www.w3.org/1999/xhtml");
                output.writeStartElement("head");
                output.writeTextElement("title", "Batch Details");
                output.writeEndElement();
                output.writeStartElement("body");
                output.writeStartElement("div");
                output.writeAttribute("style", "float: left; padding-right: 10px");
                output.writeStartElement("p");
                output.writeTextElement("strong", TTR("batchDetails", "Roasted Coffee: "));
                output.writeTextElement("span", query.value(0));
                output.writeEndElement();
                output.writeEndElement();
                output.writeStartElement("div");
                output.writeAttribute("style", "float: left");
                output.writeStartElement("p");
                output.writeTextElement("strong", TTR("batchDetails", "Roasted At: "));
                output.writeTextElement("span", batchTime);
                output.writeEndElement();
                output.writeStartElement("p");
                output.writeTextElement("strong", TTR("batchDetails", "Batch Duration: "));
                output.writeTextElement("span", query.value(1));
                output.writeEndElement();
                output.writeEndElement();
                output.writeStartElement("div");
                output.writeAttribute("style", "clear: both");
                output.writeEndElement();
                output.writeStartElement("table");
                output.writeStartElement("thead");
                output.writeStartElement("tr");
                output.writeTextElement("th", TTR("batchDetails", "Green Coffee"));
                output.writeTextElement("th", TTR("batchDetails", "Weight") + "(" + unitText + ")");
                output.writeEndElement();
                output.writeEndElement();
                output.writeStartElement("tbody");
                var items = sqlToArray(query.value(2));
                var quantities = sqlToArray(query.value(3));
                for(var i = 0; i < items.length; i++) {
                    output.writeStartElement("tr");
                    output.writeTextElement("td", items[i]);
                    output.writeStartElement("td");
                    output.writeAttribute("align", "center");
                    output.writeCharacters(Number(quantities[i]/conversion).toFixed(3));
                    output.writeEndElement();
                    output.writeEndElement();
                }
                output.writeEndElement();
                output.writeStartElement("tfoot");
                output.writeStartElement("tr");
                output.writeStartElement("td");
                output.writeAttribute("align", "right");
                output.writeTextElement("strong", TTR("batchDetails", "Green Total:"));
                output.writeEndElement();
                output.writeStartElement("td");
                output.writeAttribute("align", "center");
                output.writeCharacters(query.value(4));
                output.writeEndElement();
                output.writeEndElement();
                output.writeStartElement("tr");
                output.writeStartElement("td");
                output.writeAttribute("align", "right");
                output.writeTextElement("strong", TTR("batchDetails", "Roasted Weight:"));
                output.writeEndElement();
                output.writeStartElement("td");
                output.writeAttribute("align", "center");
                output.writeCharacters(query.value(5));
                output.writeEndElement();
                output.writeEndElement();
                output.writeStartElement("tr");
                output.writeStartElement("td");
                output.writeAttribute("align", "right");
                output.writeTextElement("strong", TTR("batchDetails", "Weight Loss:"));
                output.writeEndElement();
                output.writeStartElement("td");
                output.writeAttribute("align", "center");
                if(Number(query.value(4)) > 0) {
                    output.writeCharacters(Number(((Number(query.value(4)) - Number(query.value(5)))/Number(query.value(4))) * 100).toFixed(2));
                    output.writeCharacters("%");
                } else {
                    output.writeCharacters("unknown");
                }
                output.writeEndElement();
                output.writeEndElement();
                output.writeEndElement();
                output.writeEndElement();
                if(query.value(10).length > 0) {
                    var extradata = JSON.parse(query.value(10));
                    if(extradata.color) {
                        output.writeStartElement("p");
                        output.writeTextElement("strong", TTR("batchDetails", "Degree of Roast"));
                        output.writeEndElement();
                        if(extradata.color.whole) {
                            wholecolor.value = extradata.color.whole;
                            output.writeStartElement("p");
                            output.writeTextElement("strong", TTR("batchDetails", "Whole Bean: "));
                            output.writeTextElement("span", extradata.color.whole);
                            output.writeEndElement();
                        } else {
                            wholecolor.value = "";
                        }
                        if(extradata.color.ground) {
                            groundcolor.value = extradata.color.ground;
                            output.writeStartElement("p");
                            output.writeTextElement("strong", TTR("batchDetails", "Ground: "));
                            output.writeTextElement("span", extradata.color.ground);
                            output.writeEndElement();
                        } else {
                            groundcolor.value = "";
                        }
                    } else {
                        wholecolor.value = "";
                        groundcolor.value = "";
                    }
                } else {
                    wholecolor.value = "";
                    groundcolor.value = "";
                }
                output.writeStartElement("p");
                output.writeTextElement("strong", TTR("batchDetails", "Approved: "));
                output.writeCharacters(query.value(6));
                output.writeEndElement();
                output.writeStartElement("p");
                output.writeTextElement("strong", TTR("batchDetails", "Files: "));
                output.writeCharacters(query.value(7));
                output.writeEndElement();
                output.writeStartElement("p");
                output.writeTextElement("strong", TTR("batchDetails", "Annotations:"));
                var files = sqlToArray(query.value(7));
                var annotations = annotationFromRecord(files[0]);
                fileID = files[0];
                var buffer2 = new QBuffer("<points>"+annotations+"</points>");
                buffer2.open(1);
                var colQuery = new XQuery;
                colQuery.bind("profile", buffer2);
                colQuery.setQuery('for $i in doc($profile)//tuple[1]/temperature/@series return (string($i), ";")');
                var result = colQuery.exec();
                buffer2.close();
                var seriesHeaders = new Array();
                seriesHeaders.push(TTR("batchDetails", "Time"));
                var records = result.split(";");
                for(var i = 0; i < records.length - 1; i++) {
                    seriesHeaders.push(records[i].replace(/^\s+|\s+$/g,""));
                }
                seriesHeaders.push(TTR("batchDetails", "Note"));
                output.writeStartElement("table");
                output.writeStartElement("thead");
                output.writeStartElement("tr");
                for(var i = 0; i < seriesHeaders.length; i++) {
                    output.writeTextElement("th", seriesHeaders[i]);
                }
                output.writeEndElement();
                output.writeEndElement();
                buffer2.open(1);
                var rq = 'for $t in doc($profile) //tuple return (string($t/time), ";", ';
                for(var i = 0; i < seriesHeaders.length - 2; i++) {
                    rq += 'string($t/temperature[' + Number(i+1) + ']), ";", ';
                }
                rq += 'string($t/annotation), "~")';
                colQuery.setQuery(rq);
                var annotationData = colQuery.exec();
                colQuery = colQuery.invalidate();
                buffer2.close();
                output.writeStartElement("tbody");
                var annotationRecords = annotationData.split("~");
                for(var i = 0; i < annotationRecords.length - 1; i++) {
                    output.writeStartElement("tr");
                    var annotationRow = annotationRecords[i].split(";");
                    for(var j = 0; j < annotationRow.length; j++) {
                        output.writeStartElement("td");
                        output.writeAttribute("style", "border-left: 1px solid #000000");
                        if(j > 0) {
                            output.writeAttribute("align", "center");
                        }
                        if(j > 0 && j < annotationRow.length - 1) {
                            output.writeCharacters(Number(annotationRow[j].replace(/^\s+|\s+$/g,"")).toFixed(2));
                        } else {
                            output.writeCharacters(annotationRow[j].replace(/^\s+|\s+$/g,""));
                        }
                        output.writeEndElement();
                    }
                    output.writeEndElement();
                }
                output.writeEndElement();
                output.writeEndElement();
                output.writeCharacters(query.value(8));
                output.writeEndElement();
                output.writeEndElement();
                output.writeEndElement();
                output.writeEndDocument();
                dataView.setContent(buffer);
                buffer.close();
                log.clear();
                graph.clear();
                var buffer3 = new QBuffer(query.value(9));
                var input = new XMLInput(buffer3, 1);
                input.newTemperatureColumn.connect(log.setHeaderData);
                input.newAnnotationColumn.connect(log.setHeaderData);
                var lc;
                input.lastColumn.connect(function(c) {
                    lc = c;
                    if(c < 3) {
                        log.setHeaderData(3, "");
                    }
                });
                input.measure.connect(graph.newMeasurement);
                input.measure.connect(log.newMeasurement);
                input.annotation.connect(function(note,tcol,ncol) {
                    for(var i = tcol; i < ncol; i++) {
                        log.newAnnotation(note, i, ncol);
                    }
                });
                graph.updatesEnabled = false;
                log.updatesEnabled = false;
                input.input();
                log.updatesEnabled = true;
                graph.updatesEnabled = true;
                log.newAnnotation("End", 1, lc);
                if(query.value(6) == "true") {
                    approvalButton.checked = true;
                }
                annotationField.plainText = query.value(8);
                unitEdit.text = unitText;
                roastedEdit.text = query.value(5);
                drawTag(query.value(11), query.value(0));
                query = query.invalidate();
            }
            var saveMenu = findChildObject(this, 'save');
            saveMenu.triggered.connect(function() {
                var filename = QFileDialog.getSaveFileName(window, TTR("batchDetails", "Save Log As..."), QSettings.value("script/lastDir", "") + "/");
                if(filename != "") {
                    saveFileFromDatabase(fileID, filename);
                }
            });
            var submit = findChildObject(this, 'submit');
            submit.clicked.connect(function() {
                var query = new QSqlQuery;
                query.prepare("UPDATE roasting_log SET roasted_quantity = :roasted, approval = :approval, annotation = :annotation, additional_data = :extradata WHERE time = :time AND machine = :machine");
                query.bind(":approval", approvalButton.checked);
                query.bind(":annotation", annotationField.plainText);
                query.bind(":roasted", Number(Number(roastedEdit.text)*conversion));
                var extradata = new Object;
                var colordata = new Object;
                if(wholecolor.value.length > 0) {
                    colordata.whole = wholecolor.value;
                }
                if(groundcolor.value.length > 0) {
                    colordata.ground = groundcolor.value;
                }
                if(colordata.whole || colordata.ground) {
                    extradata.color = colordata;
                }
                query.bind(":extradata", JSON.stringify(extradata));
                query.bind(":time", batchTime);
                query.bind(":machine", Number(machine));
                query.exec();
                query = query.invalidate();
                window.loadBatch(machine, batchTime);
                displayInfo(TTR("batchDetails", "Batch Data Saved"),
                            TTR("roastspec", "New batch details saved"));
            });
            var batchTag = findChildObject(this, 'batchTag');
            var printers = findChildObject(this, 'printerlist');
            printers.currentIndex = printers.findText(QSettings.value("script/batchtagprinter"));
            printers['currentIndexChanged(int)'].connect(function() {
                QSettings.setValue("script/batchtagprinter", printers.currentText);
            });
            var printbutton = findChildObject(this, 'printbutton');
            printbutton.clicked.connect(function() {
                batchTag.print(printers.currentText);
            });
            function drawTag(item, name) {
                var buffer = new QBuffer;
                buffer.open(3);
                var output = new XmlWriter(buffer);
                output.writeStartDocument("1.0");
                output.writeDTD('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg.dtd">');
                output.writeStartElement("html");
                output.writeAttribute("xmlns", "http://www.w3.org/1999/xhtml");
                output.writeStartElement("head");
                var styleFile = new QFile(QSettings.value("config") + "/Scripts/batchtag.css");
                styleFile.open(1);
                output.writeTextElement("style", styleFile.readToString());
                styleFile.close();
                
                styleFile = new QFile(QSettings.value("config") + "/Scripts/barcode.css");
                styleFile.open(1);
                output.writeTextElement("style", styleFile.readToString());
                styleFile.close();
                
                output.writeStartElement("script");
                scriptFile = new QFile(QSettings.value("config") + "/Scripts/qrcode.js");
                scriptFile.open(1);
                output.writeCDATA(scriptFile.readToString());
                scriptFile.close();
                output.writeEndElement();
                
                output.writeStartElement("script");
                scriptFile = new QFile(QSettings.value("config") + "/Scripts/barcode.js");
                scriptFile.open(1);
                output.writeCDATA(scriptFile.readToString());
                scriptFile.close();
                output.writeEndElement();
                
                output.writeEndElement();
                output.writeStartElement("body");
                output.writeStartElement("h1");
                output.writeCharacters(name + " (" + item + ")");
                output.writeEndElement();
                output.writeTextElement("span", "Roasted at: " + batchTime);
                output.writeTextElement("span", "On machine: " + machine);
                output.writeTextElement("span", "Batch file: " + fileID);
                
                output.writeStartElement("div");
                output.writeAttribute("id", "barcode");
                output.writeAttribute("class", "barcode128h");
                output.writeAttribute("align", "center");
                output.writeEndElement();
                
                output.writeStartElement("script");
                var c128data = 'var strBarcodeHTML = code128("';
                c128data += fileID;
                c128data += '", "C");'
                c128data += 'document.getElementById("barcode").innerHTML = strBarcodeHTML;';
                output.writeCDATA(c128data);
                output.writeEndElement();
                
                output.writeStartElement("div");
                output.writeAttribute("id", "container");
                output.writeEndElement();
                output.writeStartElement("script");
                var tag = {g: "Typica", m: Number(machine), v: 1};
                tag.t = batchTime;
                tag.f = Number(fileID);
                var scriptData = 'var width = document.getElementById("container").offsetWidth;';
                scriptData += 'var qrcode = new QRCode({content: \'';
                scriptData += JSON.stringify(tag);
                scriptData += '\', width: width, height: width});';
                scriptData += 'var svg = qrcode.svg();';
                scriptData += 'document.getElementById("container").innerHTML = svg;';
                output.writeCDATA(scriptData);
                output.writeEndElement();
                output.writeEndElement();
                output.writeEndElement();
                output.writeEndDocument();
                batchTag.setContent(buffer);
                buffer.close();
            };
            var search = findChildObject(this, 'search');
            search.returnPressed.connect(function() {
                if(search.text.length == 0) {
                    return;
                }
                if(Number(search.text)) {
                    var query = new QSqlQuery();
                    query.prepare("SELECT machine, time FROM roasting_log WHERE files[1] = :file");
                    query.bind(":file", Number(search.text));
                    query.exec();
                    if(query.next()) {
                        window.loadBatch(query.value(0), query.value(1));
                    }
                    query = query.invalidate();
                } else {
                    var tag = JSON.parse(search.text);
                    if(tag.m != undefined && tag.t != undefined) {
                        window.loadBatch(tag.m, tag.t);
                    }
                }
                search.text = "";
            });
        ]]>
    </program>
</window>
