/***
Completely rewritten by Austin Cheney on 2009-04-29 to avoid using the
DOM and render standards compliant output and introduce the linediff
function.

This is part of jsdifflib v1.0. <http://snowtide.com/jsdifflib>

Copyright (c) 2007, Snowtide Informatics Systems, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the
     distribution.
   * Neither the name of the Snowtide Informatics Systems nor the names
     of its contributors may be used to endorse or promote products
     derived from this software without specific prior written
     permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***/
/* Author: Chas Emerick <cemerick@snowtide.com> */
"use strict";
var diffview = {
    /**
     * Builds and returns a visual diff view.  The single parameter, `params', should contain
     * the following values:
     *
     * - baseTextLines: the array of strings that was used as the base text input to SequenceMatcher
     * - newTextLines: the array of strings that was used as the new text input to SequenceMatcher
     * - opcodes: the array of arrays returned by SequenceMatcher.get_opcodes()
     * - baseTextName: the title to be displayed above the base text listing in the diff view; defaults
     *       to "Base Text"
     * - newTextName: the title to be displayed above the new text listing in the diff view; defaults
     *       to "New Text"
     * - contextSize: the number of lines of context to show around differences; by default, all lines
     *       are shown
     * - viewType: if 0, a side-by-side diff view is generated (default); if 1, an inline diff view is
     *       generated
     */
    buildView: function (params) {
        var baseTextLines = params.baseTextLines,
        newTextLines = params.newTextLines,
        opcodes = params.opcodes,
        baseTextName = params.baseTextName ? params.baseTextName: "Base Text",
        newTextName = params.newTextName ? params.newTextName: "New Text",
        contextSize = params.contextSize,
        inline = (params.viewType === 0 || params.viewType === 1) ? params.viewType: 0,
        thead = ["<table class='diff'><thead><tr><th></th>"],
        tbody = [],
        tfoot = ["<tr><th class='author' colspan='"],
        tdata = [],
        header,
        node = [],
        sode = [],
        rows = [],
        idx,
        change,
        code,
        b,
        be,
        n,
        ne,
        rowcnt,
        i,
        jump,
        celt = function (name, clazz) {
            var e = [];
            e[0] = "<";
            e[1] = name;
            e[2] = " class='";
            e[3] = clazz;
            e[4] = "'></";
            e[5] = name;
            e[6] = ">";
            return e.join("");
        },
        telt = function (name, text) {
            var e = [];
            text = text.replace(/\&/g, "&amp;");
            text = text.replace(/\>/g, "&gt;");
            text = text.replace(/</g, "&lt;");
            e[0] = "<";
            e[1] = name;
            e[2] = ">";
            e[3] = text;
            e[4] = "</";
            e[5] = name;
            e[6] = ">";
            return e.join("");
        },
        ctelt = function (name, clazz, text) {
            var e = [];
            text = text.replace(/\&/g, "&amp;");
            text = text.replace(/\>/g, "&gt;");
            text = text.replace(/</g, "&lt;");
            e[0] = "<";
            e[1] = name;
            e[2] = " class='";
            e[3] = clazz;
            e[4] = "'>";
            e[5] = text;
            e[6] = "</";
            e[7] = name;
            e[8] = ">";
            return e.join("");
        },
        addCells = function (row, tidx, tend, textLines, change) {
            if (tidx < tend) {
                textLines[tidx] = textLines[tidx].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0");
                row.push(telt("th", (tidx + 1).toString()));
                row.push(ctelt("td", change, textLines[tidx]));
                return tidx + 1;
            } else {
                row.push("<th></th>");
                row.push(celt("td", "empty"));
                return tidx;
            }
        },
        addCellsInline = function (row, tidx, tidx2, textLines, change) {
            row.push(telt("th", tidx === null ? "": (tidx + 1).toString()));
            row.push(telt("th", tidx2 === null ? "": (tidx2 + 1).toString()));
            if (tidx === null) {
                tidx = tidx2;
            }
            row.push(ctelt("td", change, textLines[tidx].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
        };
        if (baseTextLines === null) {
            return "Error: Cannot build diff view; baseTextLines is not defined.";
        }
        if (newTextLines === null) {
            return "Error: Cannot build diff view; newTextLines is not defined.";
        }
        if (!opcodes) {
            return "Error: Cannot build diff view; opcodes is not defined.";
        }
        if (inline) {
            header = ["<th></th>"];
            header.push(ctelt("th", "texttitle", baseTextName + " vs. " + newTextName));
        } else {
            header = [ctelt("th", "texttitle", baseTextName)];
            header.push("<th></th>");
            header.push(ctelt("th", "texttitle", newTextName));
        }
        header.push("</tr></thead><tbody>");
        thead.push(header.join(""));
        if (inline) {
            tfoot.push("3");
        } else {
            tfoot.push("4");
        }
        tfoot.push("'>Original diff view created as DOM objects by <a href='http://snowtide.com/jsdifflib'>jsdifflib</a>.  Diff view recreated as an array by <a href='http://mailmarkup.org/'>Austin Cheney</a>.</th></tr></tbody></table>");
        /**
         * Adds two cells to the given row; if the given row corresponds to a real
         * line number (based on the line index tidx and the endpoint of the 
         * range in question tend), then the cells will contain the line number
         * and the line of text from textLines at position tidx (with the class of
         * the second cell set to the name of the change represented), and tidx + 1 will
         * be returned.     Otherwise, tidx is returned, and two empty cells are added
         * to the given row.
         */
        for (idx = 0; idx < opcodes.length; idx += 1) {
            code = opcodes[idx];
            change = code[0];
            b = code[1];
            be = code[2];
            n = code[3];
            ne = code[4];
            rowcnt = Math.max(be - b, ne - n);
            sode = ["<tr>"];
            sode.push(telt("th", "..."));
            if (!inline) {
                sode.push(ctelt("td", "skip", ""));
            }
            sode.push(telt("th", "..."));
            sode.push(ctelt("td", "skip", ""));
            sode.push("</tr>");
            for (i = 0; i < rowcnt; i += 1) {
                // jump ahead if we've alredy provided leading context or if this is the first range
                if (contextSize && opcodes.length > 1 && ((idx > 0 && String(i) === contextSize) || (idx === 0 && i === 0)) && change === "equal") {
                    jump = rowcnt - ((idx === 0 ? 1 : 2) * contextSize);
                    if (jump > 1) {
                        node.push(sode.join(""));
                        b += jump;
                        n += jump;
                        i += jump - 1;
                        // skip last lines if they're all equal
                        if (idx + 1 === opcodes.length) {
                            break;
                        } else {
                            continue;
                        }
                    }
                }
                if (inline) {
                    node.push("<tr>");
                    if (change === "insert") {
                        n += 1;
                        addCellsInline(node, null, n, newTextLines, change);
                    } else if (change === "replace") {
                        if (b < be) {
                            b += 1;
                            addCellsInline(node, b, null, baseTextLines, "delete");
                        }
                        node.push("</tr><tr>");
                        if (n < ne) {
                            n += 1;
                            addCellsInline(node, null, n, newTextLines, "insert");
                        }
                        node.push("</tr>");
                    } else if (change === "delete") {
                        b += 1;
                        addCellsInline(node, b, null, baseTextLines, change);
                        node.push("</tr>");
                    } else {
                        // equal
                        if (b !== null) {
                            b += 1;
                        }
                        if (n !== null) {
                            n += 1;
                        }
                        addCellsInline(node, b, n, baseTextLines, change);
                        node.push("</tr>");
                    }
                } else {
                    node.push("<tr>");
                    b = addCells(node, b, be, baseTextLines, change);
                    n = addCells(node, n, ne, newTextLines, change);
                    node.push("</tr>");
                }
            }
        }
        rows.push(node.join(""));
        tbody.push(rows.join(""));
        tdata = [thead.join(""), tbody.join(""), tfoot.join("")];
        return tdata.join("");
    }
};