<%
  const seePrivate = await requirePerm(req, "login") === true;
  const seeEdit = await requirePerm(req, "record") === true;

  const seeDeleted = seePrivate && (req.query.deleted === "");

  const clan = await db.oneOrNone("select * from clans where clantag=$[tag]", {tag: formatTag(req.query.tag)});
  if (!clan) { %>Clan not found.<% } else {
%>
  <%- await include("partials/header.ejs", {req, res, title: "Clan " + clan.clanname}) %>
  <h3>Viewing Clan</h3>
  <p>
    <b>Clan Name</b>: <%= clan.clanname %><br />
    <b>Clan Tag</b>: <%= clan.clantag %><br />
    <br />
    <b>Point Balance</b>: <%= clan.points %><br />
    <br />
    <b>Official</b>: <%= clan.active ? "Yes" : "No" %>
  </p>
  <%
    const data = await clashAPI("https://api.clashofclans.com/v1/clans/%23" + clan.clantag + "/currentwar");
    if (data.reason && data.reason === "accessDenied") {
      %>
      <p class="winner-box">
        <b>Current War</b>: Your war log is not public.
      </p>
      <%
    }
    if (data.state === "preparation" || data.state === "inWar") {
      let result = await db.oneOrNone("select * from clans where clantag=$[clantag]", {clantag: formatTag(data.opponent.tag)});
      const otag = formatTag(data.opponent.tag);
      const oname = data.opponent.name;
      %>
      <p class="winner-box">
        <b>Current War</b> vs. <%= oname %> <%
          if (result) { %>(<a href="/clan?tag=<%= otag %>"><%= otag %></a>)<% }
          else { %>(<%= otag %>)<% }
          if (result && result.active) {
            %> is an <b>official match</b><br /><br /><%
            // calculate winner
            if (clan.points < result.points) {
              %>This clan <b>wins the war</b> by points (%><%= clan.points + " < " + result.points %>)<%
            } else if (clan.points > result.points) {
              %>This clan <b>loses the war</b> by points (%><%= clan.points + " > " + result.points %>)<%
            } else {
              // seeded random using hmac
              const pair = ([clan.clantag, otag]).sort();
              const seed = data.preparationStartTime + "," + pair.join(",");
              const hash = hmac().update(seed).digest();
              const winner = pair[hash[0] & 1];
              if (winner === clan.clantag) {
                %>This clan <b>wins the war</b> by random coin flip (%><%= clan.points + " = " + result.points %>)<%
              } else {
                %>This clan <b>loses the war</b> by random coin flip (%><%= clan.points + " = " + result.points %>)<%
              }
              %> (<a href="#show" onclick="document.getElementById('flipdetails').style.display='inline'">Show Proof</a>)
              <span id="flipdetails" style="display: none;"><br /><br />
              Hashed data: <tt><%= seed %></tt><br />
              Result hash: <tt><%= hash.toString('hex') %></tt><br />
              Sorted tags: <tt><%= JSON.stringify(pair) %></tt>
              </span><%;
            }
          } else {
            %> is a mismatch<%
          }
        %>
      </p>
      <%
    }
    %>
  <% /* TODO: pagination */ %>
  <b>Clan Point History: </b>
    <% if (seeEdit) { %> (<a href="record?tag=<%= clan.clantag %>">Add Transaction</a>/<a href="record?tag=<%= clan.clantag %>&template=sanction">Sanction</a>/<a href="record?tag=<%= clan.clantag %>&template=reward">Reward</a>)<% } %>
    <% if (seePrivate && !seeDeleted) { %> (<a href="clan?tag=<%= clan.clantag %>&deleted">See Deleted</a>)<% } %>
    <% if (await requirePerm(req, "manage") === true) { %> (<a href="audit?clantag=<%= clan.clantag %>">Audit Log</a>)<% } %>
  <table>
    <thead>
      <tr>
        <% if (seeEdit) { %><td>ID</td><% } %>
        <td>Timestamp</td>
        <td>War</td>
        <td>Points</td>
        <td>Note</td>
        <td></td>
        <td></td>
      </tr>
    </thead>
    <tbody>
      <%
      let result = await db.any("select transactions.*, wars.clanatag, wars.clanbtag, wars.data->'result' as result" +
            " from transactions left join wars on transactions.warid=wars.warid where clantag=$[clantag]" +
            (seeDeleted ? "" : " and deleted=false") +
            " order by ts desc, transid desc;", clan);
      for (let row of result) {
          let war = "";
          if (row.warid) {
            war = '<a href="war?id=' + row.warid + '">War #' + row.warid + '</a> ';
            let {result} = row;
            if (row.clanbtag === clan.clantag) result = -result;
            war += "(" + ["lose", "draw", "win"][result + 1] + ")";
          }
          %>
        <tr<%- row.deleted ? " class=\"deleted bg-gray\" style=\"text-decoration: line-through;\"" : "" %>>
          <% if (seeEdit) { %><td><%= row.transid %></td><% } %>
          <td><%= row.ts.toISOString() %></td>
          <td><%- war %></td>
          <td class="center redgreen"><%= row.points %></td>
          <td><%= row.pubnote %></td>
          <% if (seePrivate && row.privnote) { %><td class="bg-gray">Private Note: <%= row.privnote %></td><% }
          else { %><td></td><% } %>
          <td>
            <% if (row.deleted) { %>
              (DELETED)
            <% } else if (seeEdit) { %>
              (<a href="transaction?id=<%= row.transid %>">Edit</a>)
              (<a href="deltransaction?id=<%= row.transid %>">Delete</a>)
            <% } %>
          </td>
        </tr>
      <% } %>
    </tbody>
  </table>
  <% } %>
<%- await include("partials/footer.ejs", {req, res}) %>