#
type cgiinit >/dev/null 2>&1 || . ./y4-funcs.sh

blog_genform() {
  #
  t=$1 
}

blog_writable() (
  # $1=articleid $2=user
  blogowner=`getvalbyid blog owner "$1"`
  [ x"$blogowner" = x"$2" ] || isuser "$blogowner" || ismember "$2" "$blogowner"
)
blog_notify_reply() {
  # $1=articleid $2=ReplyingUser $3=WrittenText
  blogowner=`getvalbyid blog owner "$1"`
  blogtitle=`getvalbyid blog title "$1"`
  blogurl="$urlbase?replyblog+$1"
  emails=`collectemail $blogowner`
  smail "$emails" "書込通知 $urlbase"<<EOF
あなたの板に書き込みがありました。
場所: $blogurl
題目: $blogtitle
筆者: `gecos $2`
内容:
`echo "$3"|sed 's/^/> /'`
EOF
}
blog_showentry() {
  # $1=table $2=rowid
  if [ -n "$2" ]; then
    if [ -n "$imgcached" ]; then
      tmpd=$tmpdir/$imgcached/$thumbxy
    else
      tmpd=`mktempd`
      tmpfiles=$tmpfiles" $tmpd"
    fi
  fi
  tbl=${1%%[!A-Z0-9a-z_]*} rowid=${2%%[!A-Z0-9a-z_]*}
err rowid=$rowid, '$2'=$2
  ts=${tbl}_s tm=${tbl}_m
  at=article as=article_s am=article_m
  serial=$(($(date +%s)-1420038000))s$$
  # This function grasps blog entry definiton directly.
  # blog:   id
  # blog_s: title,ctime,heading
  # blog_m: *article

  err "SELECT id from $tbl where rowid=$rowid"
  id=`query "select id from $tbl where rowid=$rowid;"`
err id=$id
err "select val from $ts where key='title' and id='$id';"


  #(1)Display root article
  cat<<EOF
<form class="replyblog" action="$myname?replyblog+$rowid" method="POST" enctype="multipart/form-data">
<table class="bloghead">
EOF

  href="<a href=\"?editheading+$rowid\"> 編集 </a>"
  href2="<a href=\"?lshandout+$rowid\"> 提出状況 </a>"
  href3="(<a href=\"?gethandout+$rowid\">ファイル取得</a>)"
  cat<<EOF | sq -html $db \
      | sed -e "s|\(<TR><TD>\),e,|\1 $href |" \
	    -e "s|,s,\(</TD>\)|$href2$href3\1|"
-- select val from $ts where key="title" and id="$id";
select
 coalesce((select ",e," from blog where rowid=$rowid and author='$user'),'')
||val||" "
||case (select val from $ts where key="mode" and id="$id")
  when 'report-closed' then "レポート提出用(自身のファイルのみ参照可),s,"
  when 'report-open' then "レポート提出用,s,"
  else ""
  end
 from $ts where key="ctime" and id="$id";
select val from $ts where key="heading" and id="$id";
EOF
  cat<<EOF
</table>
<table class="blog_replies">
EOF

  #(2)Display following articles
textform='<div><table class="b">
<tr><td><textarea name="text" cols="40" rows="4"></textarea></td></tr>
<tr><td>添付ファイル: <input type="file" name="image" multiple></td></tr>
</table>
<input type="submit" value="送信">
<input type="reset" value="リセット"></div>
'
  ## 6/11の次: articleを出して行く
: <<EOF
シリアル:id:p:serial:
blogID:blogid:f:blog(id):
筆者:author:s:owner
時刻:ctime:s:stamp:
参照元:parent:s:parent: 
パス:path:s:path:
本文:text:s:textarea:cols="60" rows="8"
画像:image:m:image:
stage:stage:x:hidden:value="replyblog"

article(id, blogid, author)
article_s: Visible = ctime, text	Invisible = parent, path
article_m: image

article	=	hoge|1433812374x20849|yuuji@gentei.org
article_s =	hoge|ctime|string|2015-06-13 12:27:34|
		hoge|text|string|Shall we dance?|
EOF
  ## 
  ## 
err "select id from $at where blogid='$id';"
#  arts=`sq $db "select a.rowid,a.id,
#-- coalesce(b.gecos, a.author)
# a.author from $at a
# LEFT JOIN (select name,val as gecos from user_s where key='gecos') b
# on a.author=b.name where blogid='$id'";`
  arts=`query "select rowid,id,author from $at where blogid='$id';"`
err  arts="[$arts]"
  number=0
  hrefhome0="<a href=\"?home"
  for a in $arts; do
    arid=${a%%|*} aid=`echo "$a"|cut -d'|' -f2` author=${a##*|} imgs=""
    ### err a=$a, aid=$aid, author=$author
    # name=''	# Get gecos??
    td=$(echo $tmpd/`echo $a|md5`)
    val=`getvalbyid article image $arid $td`
err val="[$val]" and td as follows:
    
    if true; then
      if [ -n "$val" ]; then
	hrfb="$myname?showattc+article_m"
	imgs="<br>"$(echo "$val"\
		    |while read fn; do

		       #data=`percenthex $td/$fn`
		       #ct=`cat $td/$fn.content-type`
		       ri=`cat $td/$fn.rowid`
err fn=$fn ct=$ct ri=$ri; ls -lF $td/ 1>&3
		       #case $ct in
		#	 [Ii]mage*) anch="<img src=\"data:$ct,$data\">$fn" ;;
		#	 *) anch=$fn ;;
		#       esac
		       # Should not contain newlines for sed argument
		#       echo -n "<a href=\"$hrfb+$ri\">$anch</a>"
			iconhref $td/$fn "$hrfb+$ri" "$fn" "$fn"
		     done)
      fi
    fi

    ### number=$((number+1))
#    reply="<input type=\"radio\" name=\"parent\" class=\"replybtn\" \
# value=\"$number\">"
    getgecos="(select rowid from user where name='$author')||':'||\
	coalesce((select val from user_s \
	where name='$author' and key='gecos'), '$author')||',[/a],'"
    href="$myname?editart+$arid+$rowid"
    link="<a href=\"$href\">編集</a>"
    cat<<EOF | sq -html $db \
	| sed -e "s|,n,\([0-9]*\):|,n,$hrefhome0+\1\">|" \
	      -e 's|,\[/a\],|</a>|' \
	      -e 's/,n,/<br>/g' -e "s|,i,|$imgs|" \
	      -e "s|<TR>\(<TD>\)|<TR id=\"$aid\">\1|" \
	      -e "s|\(<TR.*>\)\(<TD>\),e,|\1\2$link|"
select
  coalesce((select ",e," from article where id='$aid' and author='$user'),"")
  ||
  max(case key when 'ctime' then ",n,"||val||
  ",n,"||$getgecos end) as TIME,
--  max(case key when 'parent' then val||"への返信" end) as REPLYTO,
  max(case key when 'text' then val||",i," end) as TEXT
  from article_s where id = '$aid'
  group by id order by TIME;
EOF
  done
  echo "</table>"

  
  blog_writable $rowid $user && cat<<EOF
<div class="blogcomment">
<p>コメント記入</p>
<input type="hidden" name="blogid" value="$id">
<input type="hidden" name="stage" value="replyblog">
<input type="hidden" name="serial" value="$serial">
$textform
</div>
EOF
  echo "</form>"
  
  # Record access log
  acclog blog $rowid
}

lshandout() {
  # $1=rowid of blog
  time=`getvalbyid blog ctime $1|colrm 11`
  owner=`getvalbyid blog owner $1`
  title=`getvalbyid blog title $1`
  ge=`gecos $owner`
  lshandoutsub $owner "$@" \
      |m4 -D_TITLE_="提出状況" \
	  -D_SUBTITLE_="$time [$title]@${ge:-$owner}" -D_DIARY_="" \
	  -D_FORM_="syscmd(cat)" -D_BLOGS_= -D_DUMPTABLE_= \
	  $layout/html.m4.html $layout/diary.m4.html
}
lshandoutsub() {
  # $1=owner $2=rowid of blog
  if isgroup $1; then
    sample="(select user from grp_mem where gname='$1')"
  else
    sample="(select distinct author as user from arts)"
    echo "<p>(集計は板への投稿者のみ)</p>"
  fi
  sql="with arts as (select id,author from article \
	    where blogid=(select id from blog where rowid=$2))\
      select (select rowid from user where name=c0.user)||'	'|| \
	      coalesce((select val from user_s where name=c0.user \
			and key='gecos'),\
		      c0.user) as 'メンバー',\
	     sum(case when c1.key is not null then 1 else 0 end)\
		 as 'コメント記入',\
	     sum(case when c2.key is not null then 1 else 0 end)\
		 as 'ファイルの提出'\
	 from $sample c0 \
	        left join (select id,author from arts) a\
		on c0.user=a.author\
	        left join (select id,key from article_s where key='text') c1\
		on a.id=c1.id left join (select id,key from article_m ) c2\
		on c1.id=c2.id group by c0.user order by c0.user;"
    err ishandoutsub: sql="$sql"
    echo '<table class="b td2r td3r">'
    hrb="<a href=\"?home+"
    echo "$sql" | sq -header -html $db \
	| sed -e "s,\(<TR><TD>\)\([^	]*\)	\(.*\)</TD>,\1$hrb\2\">\3</TD>," -e 's,<TD>0</TD>,<TD class="warn">0</TD>,'
    echo '</table>'
}
gethandout() {
  # $1=rowid of blog
  i=0
  bd=$tmpd/archive.$$
  mkdir $bd
  query "select m.rowid,author,m.val from article a join article_m m\
	 on a.id=m.id where blogid=(select id from blog where rowid=$1)\
	 and m.key in ('image', 'document', 'binary');" \
      | while IFS='|' read rowid author filename; do
	  # err isfilereadable $user article_m $1
	  isfilereadable $user article_m $1 || continue
	  err ok
	  i=$((i+1))
	  dir=`printf $bd/%03d $i`
	  mkdir $dir
	  query "select quote(bin) from article_m where rowid=$rowid;" \
	      | unhexize > $dir/$filename
	done
  if [ ! -d $bd/001 ]; then
    contenttype; echo
    echo "<p>取得できるファイルがありませんでした。</p>"
    return
  fi
  (cd $bd
   err cdto$bd; (pwd; ls -lFa) 1>&3
   tar zcf .archive.tar.gz * && mv .archive.tar.gz archive.tar.gz
  )
  arc=$bd/archive.tar.gz
  echo "Content-type: application/x-gzip"
  echo "Content-Length: `cat $arc|wc -c`"
  echo "Content-Disposition: filename=\"archive.tar.gz\""
  echo
  cat $arc
}

listblog() (
  # $1=user
  cond="where a.id in (select id from blog_s where key='owner' and val='$1') order by ctime desc"
  DT_CHLD=article:blogid
  cgi_form searchart<<EOF
<label>`cgi_text kwd`という語を含む記事を検索</label>
`cgi_hidden owner $user`
EOF
  dumptable html blog 'ctime title heading' "$cond"
)

blog_addentry() {
  # $1=GRPname(if it is a group)
  grp=$1
  rowid=`getpar rowid`
err ba: rowid=$rowid
  #if [ -z "$rowid" ]; then
    # When rowid is SET, it is updation of existing entry
    if [ -z "$1" ]; then
      listing=$user guide="[個人]"
#listing代入は rowid 時でもするべき
    else
      if isgroup $1; then
	listing=$1 guide="[${1}]" GF_OWNER=$1
      else
	echo "<p>無効なグループ指定です。</p>"
	return
      fi
    fi
  #fi
  if [ -n "`getpar title`" ]; then
    owner=`getpar owner`
    if isuser $owner; then
      if [ x"$user" != x"$owner" ]; then
	echo "<p>他人の日記は書けません</p>"
	return
      fi
    elif isgroup $owner; then	# if write to group log
      grp=$owner #\`getpar grp\`
      err ismember: $user $grp
      if ! ismember "$user" "$grp"; then
	echo "<p>(話題作成はこのグループに加入してから)</p>"
	return
      fi
    fi
    par2table $formdir/blog.def
    serial=`getpar serial`
    err SERIAL: $serial ROWID=$rowid listing=$listing
    id=""
    if [ -n "$rowid" ]; then
      # Here, id becomes NULL when removal of entries at par2table
      id=`query "select rowid from blog where rowid=$rowid;"`
    elif [ -n "$serial" ]; then
      # If new blog leader created, traverse to its head.
      id=`query "select rowid from blog where id='$serial';"`
    fi
    if [ -n "$id" ]; then
      ## If new aritcle is entered, JUMP to blog_reply
      blog_reply $id
      return
    fi
  fi
  m4 -D_TITLE_="${guide}新規話題作成" -D_DIARY_="新規話題の記入" \
     -D_SUBTITLE_="序文は簡単に詳しくはコメントに" \
     -D_BLOGS_="これまでの蓄積" \
     -D_FORM_="`genform $formdir/blog.def`" \
     -D_DUMPTABLE_="`listblog $listing`" \
     $layout/html.m4.html \
     $layout/diary.m4.html
}

blog_reply() {
  rowid=$1
err  rowid=$1

  if [ -z "$rowid" ]; then
    echo "<p>表示する日記番号が未指定です。</p>"
    return
  fi
  title=`getvalbyid blog title $rowid`
  owner=`getvalbyid blog owner $rowid`
  if isuser "$owner"; then
    subtitle="`gecos $owner` さんの話題"
  else
    subtitle="<a href=\"?grp+$owner\">`gecos $owner`</a> での話題"
  fi
  if [ -z "$title" ]; then
    echo "<p>日記番号指定が無効です。</p>"
    return
  fi

  text=`getpar text`
  if [ -n "$text" ]; then
    if blog_writable $rowid $user; then
      if par2table $formdir/article.def; then
	blog_notify_reply $rowid $user "$text"
      fi
    else
      title="$title(加入してないので書き込み不可)"
    fi
  fi
  def=$formdir/article.def
  cat $layout/html.m4.html $layout/diary.m4.html \
      | sed '/_DIARY_/q' \
      | m4 -D_TITLE_="$title" -D_DIARY_="" -D_BODYCLASS_=general \
	   -D_SUBTITLE_="$subtitle"
  blog_showentry blog $rowid
  sed '1,/_DIARY_/d' $layout/diary.m4.html | m4 -D_FORM_= -D_DUMPTABLE_=
}
