<!--
This is the template file for displaying query results.

## $Id: select_result.tmpl 332 2006-10-11 17:11:48Z michi2 $
-->

<%
from trio.common import TYPE_UNCERTAIN, TYPE_CONFIDENCE, TYPE_CERTAIN
from cgi import escape
hasLineage = None
%>

<div class="box">
% if c.results.error is not None:

    ##
    ## Query returned an error. Print the error message.
    ##
    <div class="box_header">Query Result</div>
    <p><span class="error">ERROR</span>: ${c.results.error}</p>

% elif not c.results.isFetchable:

    ##
    ## TODO: Right now there is no way of knowing what type of query
    ## got executed. Find a way to better support non-select queries.
    ##

    <div class="box_header">Query Result</div>
    <p><span class="success">SUCCESS</span>: TriQL command succeeded.</p>

% else:

    ##
    ## It looks like this is a result of a select query. Print the result.
    ##

    <%
    tupleIndex = c.results.getPage() * c.results.pageSize
    %>
    <div class="box_header">
    <div class="box_header_left">Query Result</div>
    <div class="box_header_right">

    % if len(c.results.results) > 0:
        ##
        ## Print the range of tuples displayed.
        ## e.g. "1 -  10  of 113 xtuple(s)"
        ##
        <span class="bold">
        ${c.results.getPage() * c.results.pageSize + 1}
        </span> -
        <span class="bold">
        ${min(c.results.getNumResults(), (c.results.getPage() + 1) * c.results.pageSize)}
        </span> of
    % endif

    <span class="bold">${c.results.getNumResults()}</span> tuple(s)
    </div>
    <div class="spacer"></div>
    </div>
    <br />
    <p>

    ##
    ## Here comes the messy part. Display the query result.
    ##
    <table class="results">

    ## Print out the header with attribute names.
    <tr>

    ## An empty cell.
    <th class="nontuple"></th>

    ## Attribute names.
    % for k in range(len(c.results.schema)):
        % if k in c.results.u_columns:
            <th class="tuple${c.results.type}">${c.results.schema[k][0].lower()}*</th>
        % else:
            <th class="tuple${c.results.type}">${c.results.schema[k][0].lower()}</th>
        % endif
    % endfor

    ## Question mark.
    <th class="nontuple">
    % if c.results.type == TYPE_CONFIDENCE and c.results.conf_computed == False:
        <%
        indexurl = "index?query=%s&compconf=True&page_num=%s" % (c.query, str(c.results.getPage()))
        %>
        <div class="conf-box${c.results.type}"><a href="${indexurl}">CONF-ALL</a></div>
    % endif
    </th>

    ## An empty cell.
    <th class="nontuple"></th>

    </tr>

    <%
    num = len(c.results.schema) + 3
    %>
    <tr><td colspan="${num}" class="blank"></td></tr>

    <%
    summary = []
    i = 0
    k = 0
    sequence = session['user'].sequence
    %>

    % for tuple in c.results.getResults():

        <%
        hidden_id = "hide" + str(sequence[0])
        sequence[0] = sequence[0] + 1
        shown_id = "show" + str(sequence[0])
        sequence[0] = sequence[0] + 1
        image_id = "image" + str(sequence[0])
        sequence[0] = sequence[0] + 1
        i = i + 1
        summary = []

        ## Put an xtuple into a list of lists, where each list
        ## consists of value(s) of an attribute.
        for attr in c.results.schema:
            summary.append([])

        for alt in tuple:
            for j in range(len(summary)):
                if isinstance(alt[j], basestring):
                    val = escape(alt[j], True)
                elif alt[j] is not None:
                    val = str(alt[j])
                else:
                    val = "NULL"
                if not val in summary[j]:
                    summary[j].append(val)
        alts = ""
        %>

        ##
        ## This part is hidden if there is more than one alternative.
        ## It shows up when user clicks on the + button.
        ##
        % if len(tuple) > 1:
            <tbody id="${hidden_id}" class="hidden-rows">
        % else:
            <tbody id="${shown_id}">
        % endif

        <%
        tc = c.tcnx.cursor()
        altIndex = 0
        %>

        % for index in range(len(tuple)):
            <%
            alt = tuple[index]
            lin = alt.getLineage()
            %>
            % if hasLineage is None:
                % for table in lin.tables():
                    <%
                    tc.execute("\l %s" % table)
                    %>
                    % if tc.rowcount > 0:
                        <%
                        hasLineage = True
                        break
                        %>
                    % endif
                % endfor
                % if hasLineage is None:
                    <%
                    hasLineage = False
                    %>
                % endif
            % endif
            <%
            aidlist = lin.aidstrs()
            lineage_id = "lineage" + str(sequence[0])
            sequence[0] = sequence[0] + 1
            image_id = "image" + str(sequence[0])
            sequence[0] = sequence[0] + 1
            aids2 = ",".join(aidlist)
            tables2 = ",".join(lin.tables())
            disj2 = ",".join(str(x) for x in lin.disjlin)
            %>

            <tr>
            ## lineage button
            <td class="nontuple">
            % if not c.results.nolineage and (not c.results.isViewTable or hasLineage):
                <%
                image_id = "image" + str(sequence[0])
                sequence[0] = sequence[0] + 1
                url = "lineage?tables=" + tables2 + "&aids=" + aids2 + "&disj=" + disj2
                if not c.results.isViewTable and not c.results.distinct:
                    url += "&top=t"
                endif
                %>
                <a href="javascript:xmlhttpPost('${url}', '${lineage_id}', '${image_id}');" id="${image_id}">
                <img title="Show lineage of this alternative" src="img/down.gif" alt="+" />
                </a>
            % endif

            % if c.results.extlineage:
            ## and (not c.results.isViewTable):
                <%
                image_id = "image" + str(sequence[0])
                sequence[0] = sequence[0] + 1
                url = "extlineage?tables=" + tables2 + "&aids=" + aids2
                %>
                <a href="javascript:xmlhttpPost('${url}', '${lineage_id}', '${image_id}');" id="${image_id}">
                <img title="Show lineage of this alternative" src="img/down-red.gif" alt="+" />
                </a>
            % endif
            </td>

            ## attributes
            % for k in range(len(alt)):
                <%
                aidlist = ",".join(map(str, alt.lineage.aids()))
                %>
                % if len(tuple) > 1:
                    <td class="alternative" onclick="toggle('${hidden_id}', '${shown_id}');"
                        title="xid(s): ${str(tuple.xid).replace("_", ",")}, aid(s): ${aidlist}">
                % else:
                    <td class="nonclickable-alternative" title="xid(s): ${str(tuple.xid).replace("_", ",")}, aid(s): ${aidlist}">
                % endif

                % if alt[k] is not None:
                    % if k in c.results.u_columns:
                        <span class="uncertain">${alt[k] | h}</span>
                    % else:
                        <b>${alt[k] | h}</b>
                    % endif
                % else:
                    % if k in c.results.u_columns:
                        <span class="uncertain">NULL</span>
                    % else:
                        <b>NULL</b>
                    % endif
                % endif

                </td>
            % endfor

            ## confidence/question mark
            <td class="nontuple">
            % if c.results.type == TYPE_CONFIDENCE:
                % if alt.getConfidence() == None:
                    <%
                    image_id = "image" + str(sequence[0])
                    sequence[0] = sequence[0] + 1
                    conf_id = "conf" + str(sequence[0])
                    sequence[0] = sequence[0] + 1
                    url = "confidence?table=" + tables2 + "&aid=" + aids2 + "&disj=" + disj2 + \
                    "&xindex=" + str(tupleIndex) + "&aindex=" + str(altIndex)
                    %>
                    <div class="conf-box${c.results.type}">
                    <a href="javascript:getConfidence('${url}', '${conf_id}', '${image_id}');"
                       id="${image_id}" title="Get confidence of this alternative">conf</a>
                    <span id="${conf_id}"></span>
                    </div>
                % else:
                    <div class="conf-box${c.results.type}">
                    % if isinstance(alt.getConfidence(), float):
                        ${"%.3f" % alt.getConfidence()}
                    % else:
                        ${alt.getConfidence()}
                    % endif
                    </div>
                % endif
            % elif c.results.type == TYPE_UNCERTAIN:
                % if tuple.getQuestionMark(c.results.version):
                    <div class="question-box">? </div>\
                % endif
            % endif
            </td>

            ## version
            <td class="nontuple">
            % if alt.start != -1 and alt.end != -1:
                <i>[${alt.start},${(alt.end < 1<<30 and str(alt.end) or "&infin;")})</i>
            % endif
            </td>
            </tr>

            ## The lineage of this alternative comes here.
            <tr class="lineage">
            <td class="lineage-noborder"></td>
            <td id="${lineage_id}" colspan="${len(summary)}" class="lineage"></td>
            <td class="lineage-noborder"></td>
            </tr>
            <%
            num2 = len(summary) + 2
            altIndex =  altIndex + 1
            %>
        % endfor
        </tbody>

        ##
        ## Display the xtuple summary if and only if there is more than one
        ## alternative
        ##
        % if len(tuple) > 1:
            <tbody id="${shown_id}">
        % else:
            <tbody id="${hidden_id}" class="hidden-rows">
        % endif
        <tr class="xtuple">
        <td class="nontuple"></td>

        ## Display summary of attributes
        <%
        count = 0
        %>
        % for val in summary:
            <%
            if count in c.results.u_columns:
                for num in range(len(val)):
                   val[num] = '<span class="uncertain">' + val[num] + '</span>'
                endfor
            else:
                for num in range(len(val)):
                   val[num] = '<b>' + val[num] + '</b>'
                endfor
            endif
            joinstr = """<span class="separator""" + str(c.results.type) + """"> || </span>"""
            if len(val) < 5:
                alts = joinstr.join(val)
            else:
                alts = joinstr.join(val[:4]) + (" <I>[%s more...]</I>" % (len(val)-4))
            endif
            %>
            % if count == 0:
                <td class="xtupleleft${c.results.type}"
                    onclick="toggle('${hidden_id}', '${shown_id}');">${alts}</td>
            % else:
                <td class="xtuple${c.results.type}"
                    onclick="toggle('${hidden_id}', '${shown_id}');">${alts}</td>
            % endif
            <%
            count = count + 1
            %>
        % endfor

        ## Display confidence/question mark if necessary.
        <td class="nontuple">
        % if c.results.type == TYPE_CONFIDENCE:
            % if tuple.getConfidence(c.results.version) is not None:
                <div class="conf-box${c.results.type}">${"%.3f" % tuple.getConfidence(c.results.version)}</div>
            % else:
                <%
                indexurl = "index?query=%s&compconf=True&page_num=%s&xindex=%s" % \
                           (c.query, str(c.results.getPage()), str(tupleIndex))
                %>
                <div class="conf-box${c.results.type}"><a href="${indexurl}">conf</a></div>
            % endif
        % elif c.results.type == TYPE_UNCERTAIN:
            % if tuple.getQuestionMark(c.results.version):
                <div class="question-box">?</div>
            % endif
        % endif
        </td>
        </tr>
        </tbody>
        <tr><td colspan="${num2}" class="blank"></td></tr>
        <%
        tupleIndex = tupleIndex + 1
        %>
    % endfor

    <%
    c.tcnx.commit()
    %>

</table>
</p>

## Print page navigation.
<p>${c.results.getPageNav()}</p>

% endif
</div>
