#-- set a couple of variables
proc ui::vars {} {
   #-- import
   set current_page $::current_page
   set baseurl $::baseurl

   #-- export variables
   upvar 1 pagecat pagecat            # index | wcontent | wiki | tree | timeline
   upvar 1 pagename pagename          # src/data
   upvar 1 basedomain basedomain
   upvar 1 stats_description stats_description
   upvar 1 stats_social stats_social
   upvar 1 stats_forks stats_forks

   #-- Determine current page type
   set pagename ""
   if {[regexp {^(index|home)[?]?} $current_page]} {
      set pagecat "index"
   } else { if {[regexp {^wiki\?name=} $current_page]} {
         set pagecat "wiki"
         set pagename [string range $current_page 10 2048]
   } else {
      set pagecat $current_page
   } }

   #-- Split domain name from baseurl
   set basedomain [string range $baseurl [expr 7+[expr {[string range $baseurl 4 4] eq "s"}]] [expr 7+[string first "/" [string range "$baseurl/" 8 50]]]]

   #-- Project stats
   set stats_description [setting project-description]
   set stats_social 0
   set stats_forks 1
   catch { query { SELECT name,value FROM fx_stats WHERE name GLOB 'stats_*' } {
      set "$name" "$value"
      upvar 1 $name $name
   } }
}


#-- For outputting class=current in #sidebar
proc current {name} {
   upvar 1 pagecat pagecat
   if [regexp "^($name)" $pagecat] { puts { class=current} }
}


#-- Turn config:sitemap-* urls into button links
proc ui::sitemap_links {} {
   set color "green"
   foreach name "download docidx license contact changelog news freshcode repository doap project.json" {
      set url [setting sitemap-$name]
      if {[string length $url]} {
         html "<a href='$url' class='button $color proj-sitemap'>$name</a>"
      }
      set color "white"
   }
}

#-- Ordered list of project statistics (will populate global $stats() array)
proc ui::stats {} {
   uplevel 1 { query {SELECT
     (SELECT count(objid) FROM event WHERE type='ci' LIMIT 1) AS `stats_checkins`,
     (SELECT count(name) FROM filename LIMIT 1) AS `stats_files`,
     (SELECT count(status) FROM ticket LIMIT 1) AS `stats_tickets`,
     (SELECT count(DISTINCT user) FROM event LIMIT 1) AS `stats_developers`,
     (SELECT count(DISTINCT value) FROM tagxref WHERE tagid=8) AS `stats_branches`,
     (SELECT count(tagname) FROM tag WHERE tagname LIKE 'sym-%') AS `stats_tags`,
     (SELECT count(tagname) FROM tag WHERE tagname REGEXP '^sym[-a-z0-9_.]+\d+\.\d+') AS `stats_releases`
   } {} }
}

#-- Language/Content statistics (outputs colored bar graph)
proc ui::lang_stats {} {
   # fetch $lang(js/...), $lang_color(js), $lang_list, $total_size
   query {SELECT name, value FROM fx_stats ORDER by VALUE DESC} {
      set $name $value
   }
   # output color bar for language proportions
   #html "<div class=language-bar style='width:100%; height:3pt; box-sizing:border-box;'>"
   foreach name $lang_list {
      set percent "[expr $lang($name)*100]%"
      html "<span class=code-rate-$name style='height:100%; width:$percent; display:inline-block; background-color:#$lang_color($name)' title='$percent $name'></span>";
   }
   #html "</div>";
}

#-- print two table rows for last commit
proc ui::last_commit {} {
   query {
       SELECT *, CAST(julianday('now')-mtime AS INT) AS age, substr(comment,0,199) AS msg, substr(uuid, 0, 10) AS short_uuid
       FROM event JOIN blob ON blob.rid=event.objid
       WHERE type='ci' ORDER BY mtime DESC LIMIT 1
   } {
      html "  <tr><th colspan=3>$msg</th></tr>";
      html "  <tr><th colspan=3 style=background:#fff><a href='timeline?u=$user' class=user>$user</a> authored $age days ago
            <span style=float:right>last checkin <a href='ci/$uuid'>$short_uuid <span class=glyph>&#x2398;</span></a></span></th></tr>";
   }
}

#-- outputs table rows containing top-level filenames and recent checkin comments
proc ui::recent_files {dirname} {
   set seen "(.gitignore)"
   
   # search files using directory as base path
   set branch "trunk"
   set cutname 0
   set AND_DIR ""
   if {[string length $dirname]} {
       set dirname "$dirname/"
       set cutname [string length $dirname]
       set AND_DIR " AND substr(name, 0, \$cutname+1) = \$dirname "
   }

   # files   // vcache.rid=mlink.fid would be easier to skip deleted files, but access is prohibited(?)
   query "
       SELECT DISTINCT
          m.fnid, m.fid, MAX(m.mid),
          INSTR(SUBSTR(name,\$cutname+1),'/')>0  AS  is_dir,
          name                                AS  pathname,
          bf.rid   AS  fn_rid,     bf.uuid    AS  fn_uuid,
          bm.rid   AS  ci_rid,     bm.uuid    AS  ci_uuid,
          SUBSTR(comment, 0, 70)              AS  comment,
          CAST(JULIANDAY('now')-e.mtime AS INT) AS  age
       FROM
          filename
          LEFT JOIN mlink m ON m.fnid = filename.fnid
          LEFT JOIN tagxref ON m.mid = tagxref.rid
          LEFT JOIN blob bf ON bf.rid = m.fid
          LEFT JOIN blob bm ON bm.rid = m.mid
          LEFT JOIN event e ON e.objid = m.mid
       WHERE
          tagxref.value = \$branch
          $AND_DIR
       GROUP BY
          name
       HAVING
          fid <> 0
       ORDER BY
          is_dir DESC, name ASC, e.mtime DESC
   " {

      # separate directories and files
      set name [string range $pathname $cutname 2048]
      set dir [string first "/" $name]
      if {$dir>0} { set name [string range $name 0 [expr $dir-1]] }

      # skip seen files
      if [str::contains "($name)" $seen] { continue } else { set seen "($name),$seen" }
      
      # output table entries
      html "               <tr><td>";
      if {$dir>0} {
          # if there is an equivalent wiki page for a directory, then we mix filebox + wiki
          set display "wiki"
          #set display [?: [sql::page_exists "$dirname$name"] "wiki" "tree"]
          html "<a class=dir href='$display/[htmlize $dirname$name]'><b class=glyph>📂</b> [htmlize $name]</a>";
      } else {
          html "<a class=file href='artifact/$fn_uuid'><b class=glyph>📄</b> [htmlize $name]</a>";
      }
      html "</td> <td>[htmlize $comment]<a href='ci/$ci_uuid'>‹›</a></td> <td>[htmlize $age] days ago</td></tr>\n";
   }
}

#-- social media share links
proc ui::social_links {baseurl} {
  html "
   <a class=sml-go href='https://plus.google.com/share?url=$baseurl' title=google+>g+</a> &middot;
   <a class=sml-fb href='https://www.facebook.com/sharer/sharer.php?u=$baseurl' title=facebook>fb</a> &middot;
   <a class=sml-tw href='https://twitter.com/intent/tweet?url=$baseurl' title=twitter>tw</a> &middot;
   <a class=sml-rd href='http://reddit.com/submit?url=$baseurl' title=reddit>rd</a> &middot;
   <a class=sml-in href='https://www.linkedin.com/shareArticle?mini=true&amp;url=$baseurl' title=linkedin>in</a> &middot;
   <a class=sml-su href='https://www.stumbleupon.com/submit?url=$baseurl' title=stumbleupon>su</a> &middot;
   <a class=sml-dl href='https://del.icio.us/post?url=$baseurl' title=delicious>dl</a>
  ";
}

