<%
from trio.common import TYPE_UNCERTAIN, TYPE_CONFIDENCE, TYPE_CERTAIN

tc = c.tcnx.cursor()
tnc = c.tcnx.ncursor()
lin_xtups, lin_tables, lin_ttypes, descriptions, lin_disj = [], [], [], [], []
u_columns = []
sequence = session['user'].sequence
linclass = "tuple"
if not c.top:
    sql = "SELECT aid, srclin, srctable, disjlin FROM trio_lin_%s WHERE aid = %s ORDER BY disjlin ASC"
    t = c.tables[0]
    a = c.aids[0]
    sql = sql % (t, a)
    tnc.execute(sql)
    lins = tnc.fetchall()
    j = 0
    l = 1
    for lin in lins:
        lin_tname = lin[2]
        lin_aid   = lin[1]
        tc.execute('\\t %s' % lin_tname)
        ttype = tc.fetchone()[0]
        lin_ttypes.append(ttype)
        tc.execute("View Table %s Where trio_aid = %s At Any Version" % (lin_tname, lin_aid))
        lin_xtup = tc.fetchone()
        descriptions.append(tc.description)
        lin_tables.append(lin_tname)
        lin_xtups.append(lin_xtup)
        lin_disj.append(lin[3])
        u_columns.append(tc.u_columns)
        j += 1
else:
    lin_disj = c.disj
    for i in range(len(c.tables)):
        t = c.tables[i]
        a = c.aids[i]
        tc.execute('\\t %s' % t)
        ttype = tc.fetchone()[0]
        lin_ttypes.append(ttype)
        tc.execute("View Table %s Where trio_aid = %d At Any Version" % (t, int(a)))
        lin_xtup = tc.fetchone()
        descriptions.append(tc.description)
        u_columns.append(tc.u_columns)
        lin_tables.append(t)
        lin_xtups.append(lin_xtup)
%>

% for i in range(len(lin_xtups)):
    % if len(lin_disj) > 1 and i > 0 and lin_disj[i] - lin_disj[i - 1] == 1:
        <hr />
        <center><!--<i>or</i>--></center>
        <hr style="margin: 0px" />
    % endif
    % if len(lin_disj) > 1 and i > 0 and lin_disj[i] - lin_disj[i - 1] == 2:
        <hr style="margin: 0px; color: #c0c0Cc; background-color: #c0c0Cc; height: 10px;" />
    % endif
    % if len(lin_disj) > 1 and i > 0 and lin_disj[i] - lin_disj[i - 1] == 3:
        <hr style="margin: 0px;  color: #ff3366; background-color: #ff3366; height: 5px;" />
    % endif
    <%
    hasLineage = False
    tc.execute("\\l %s" % lin_tables[i])
    if tc.rowcount > 0:
        hasLineage = True
    if lin_xtups[i]:
        query = "View Table %s" % lin_tables[i]
        #query = "View Table %s Where trio_xid = %s" % (lin_tables[i], lin_xtups[i].xid)
    else:
        query = "View Table %s" % lin_tables[i]
    att = []
    for k in range(len(descriptions[i])):
        if k in u_columns[i]:
            att.append(descriptions[i][k][0] + "*")
        else:
            att.append(descriptions[i][k][0])
    attr = ", ".join(att)
    schema = attr
    cols = len(att)
    %>

    <table class="lineage">

    ## Show schema info.
    <tr>
    <th class="nontuple"></th>
    <th colspan="${cols}" class="nontuple"><a class="link${lin_ttypes[i]}"
        href="?query=${query}">${lin_tables[i].upper()}  (${attr})</a></th>
    <th class="nontuple"></th>
    </tr>

    ## Show the blue "lineage" button.
    <tr>
    <td class="nontuple">
    <%
    x=0
    if lin_xtups[i]:
        lin_alt=lin_xtups[i][0]
        aid = lin_alt.getLineage().aids()[0]
        xid = lin_xtups[i].xid
        url = "lineage?tables=%s&aids=%s" % (lin_tables[i], str(aid))
        lineage_id = str(sequence[0])
        sequence[0] = sequence[0] + 1
        image_id = str(sequence[0])
        sequence[0] = sequence[0] + 1
    %>
    % if lin_xtups[i] and hasLineage:
        <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>
    % else:
        <img class="hidden" title="-" src="img/up.gif" alt="+" />
    % endif
    </td>

    ## Print alternative.
    % if lin_xtups[i]:
        % for j in range(len(lin_alt)):
            % if j in u_columns[i]:
                % if lin_alt[j] is not None:
                    <td class="${linclass}" title="xid:${xid}, aid:${aid}">
                    <span class="uncertain">${lin_alt[j]}</span></td>
                % else:
                    <td class="tuple" title="xid:${xid}, aid:${aid}"><span class="uncertain">NULL</span></td>
                % endif
            % else:
                % if lin_alt[j] is not None:
                    <td class="${linclass}" title="xid:${xid}, aid:${aid}"><b>${lin_alt[j]}</b></td>
                % else:
                    <td class="tuple" title="xid:${xid}, aid:${aid}"><b>NULL</b></td>
                % endif
            % endif
        % endfor
    % endif

    <td class="nontuple">
    % if lin_xtups[i] and lin_ttypes[i] == TYPE_CONFIDENCE:
        % if lin_alt.getConfidence() is None:
            <%
            image_id = str(sequence[0])
            sequence[0] = sequence[0] + 1
            conf_id = str(sequence[0])
            sequence[0] = sequence[0] + 1
            url = "confidence?table=" + lin_tables[i] + "&aid=" + str(aid)
            %>
            <div class="conf-box${lin_ttypes[i]}">
            <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${lin_ttypes[i]}">
            % if isinstance(lin_alt.getConfidence(), float):
                ${"%.3f" % lin_alt.getConfidence()}
            % else:
                ${lin_alt.getConfidence()}
            % endif
            </div>
        % endif
    % elif lin_xtups[i] and lin_ttypes[i] == TYPE_UNCERTAIN:
        % if lin_alt.getQuestionMark():
            <div class="question-box">? </div>
        % endif
    % endif
    </td>

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

    ## Show the lineage of this alternative (when user clicks the blue button)
    % if lin_xtups[i]:
        <tr>
        ## Blank column for indentation.
        <td class="nontuple"></td>
        <td class="hidden" id="${lineage_id}" colspan=${len(lin_alt)}"  ></td>
        <td class="nontuple"></td>
        </tr>
    % endif

    </table>

% endfor

<%
c.tcnx.commit()
session.save()
%>
