# Copyright for the Uniform Repository Service (c) 1995 - 2019,
# by Gerald Banon. All rights reserved.
# Version 2.1
# statistics.tcl
# Example:
# http://$site/statistics.cgi/$rep
# http://banon-pc.dpi.inpe.br:1905/statistics.cgi/dpi.inpe.br/banon/1995/09.18.18.50
# PATH_INFO = /dpi.inpe.br/banon/1995/09.18.18.50

# QUERY_STRING = returnaddress=<address>

proc Statistics {} {
	global searchResultList
	global numberOfSites
	global numberOfSatisfiedQueries
	global env
	global cgi
	global currentRep
	global mirrorHomePageRep	;# defined in FindLanguage (utilities1.tcl)
	global homePath	;# used in FindLanguage
	global loBiMiRep	;# used in MultipleSubmit (called in FindSiteContainingTheOriginal2)
	global serverAddress	;# used in SetFieldValue

#	array set environment [array get env]	;# used in MultipleSubmit

	set monthAbbreviation(01) Jan
	set monthAbbreviation(02) Feb
	set monthAbbreviation(03) Mar
	set monthAbbreviation(04) Apr
	set monthAbbreviation(05) May
	set monthAbbreviation(06) Jun
	set monthAbbreviation(07) Jul
	set monthAbbreviation(08) Aug
	set monthAbbreviation(09) Sep
	set monthAbbreviation(10) Oct
	set monthAbbreviation(11) Nov
	set monthAbbreviation(12) Dec
	
	set col ../../../../..

# currentRep	
	set currentRep $env(LOBIMIREP)	;# used by MultipleSubmit
# URLibServiceRepository
	set URLibServiceRepository $env(URLIB_SERVICE_REP)
# homePath (used in FindLanguage)
	set homePath $env(DOCUMENT_ROOT)
# loBiMiRep
	set loBiMiRep $env(LOBIMIREP)	;# used in MultipleSubmit (called in FindSiteContainingTheOriginal2)

	source ../$col/$URLibServiceRepository/doc/utilities1.tcl
	source ../$col/$URLibServiceRepository/doc/cgi/mirrorfind-.tcl

# Find the language and the language repository
# use the same languages as used for the local bibliographic mirror
	foreach {language languageRep1 languageRep2} [FindLanguage $env(LOBIMIREP)] {break}
# Find the language and the language repository - end

if [info exists env(QUERY_STRING)] {
	foreach {name value} [split $env(QUERY_STRING) &=] {
		set cgi([DecodeURL $name]) [DecodeURL $value]
	}
}

## site
# 	set site $env(HTTP_HOST)

# bgColor, background and bgProperties
	foreach {bgColor background bgProperties fontTag fontTag2} [GetBg $languageRep1 $language] {break}
	set background [subst $background]
 
	source ../$col/$languageRep2/doc/mirror/${language}Statistics.tcl
	global "${languageRep2}::Average number of visits per day"
	global "${languageRep2}::over 10 periods of \$periodLength days"
	global "${languageRep2}::The red period number indicates that the corresponding period contains the day May 17, 2015<sup>1</sup>."
	global "${languageRep2}::The height of each purple bar is proportional to the average\
number of visits per day<BR>within the corresponding period."
	global "${languageRep2}::Period 1 begins on \$startingDay"
	global "${languageRep2}::and Period 10 ends on \$todayDate"
	global "${languageRep2}::The number of visits over the 10 periods is \
<B>\$totalNumberOfVisits</B>."
	global "${languageRep2}::The average number of visits per day over the 10 periods is \
<B>\$average</B>."
	global "${languageRep2}::These statistics have been extracted from \$numberOfActiveSites \
out of \$numberOfSites sites."
	global "${languageRep2}::<sup>1</sup>Before May 17, 2015, all each user visits (IP) were added, thereafter, \
only one visit per day for each user (IP) is added."
# accessdate
	global "${languageRep2}::accessDate"
	global "${languageRep2}::Jan"
	global "${languageRep2}::Feb"
	global "${languageRep2}::Mar"
	global "${languageRep2}::Apr"
	global "${languageRep2}::May"
	global "${languageRep2}::Jun"
	global "${languageRep2}::Jul"
	global "${languageRep2}::Aug"
	global "${languageRep2}::Sep"
	global "${languageRep2}::Oct"
	global "${languageRep2}::Nov"
	global "${languageRep2}::Dec"

	global "${languageRep2}::Return"

puts {Content-Type: text/html}
puts {}

# rep
	regsub -all { } [lrange [file split $env(PATH_INFO)] 1 4] {/} rep

## serverAddressWithIP
#	set serverAddressWithIP [list $env(IP_ADDR) $env(URLIB_PORT)]
# serverAddress
	set serverAddress [list $env(SERVER_NAME) $env(URLIB_PORT)]

# Get metadata
	set siteContainingTheOriginal [FindSiteContainingTheOriginal2 $rep 0]	;# without ip
# puts $siteContainingTheOriginal
	if ![string equal {} $siteContainingTheOriginal] {
		set serverAddress $siteContainingTheOriginal
	}

	set metadataRep [Execute $serverAddress [list FindMetadataRep $rep]]
	SetFieldValue $serverAddress $metadataRep-0 {referencetype title author year}
	set referenceType $referencetype
	set author [FormatAuthorList $author]
	set author "$author :$year:"
# Get metadata - end

# Compute the todayDate
# today
	set today [clock format [clock seconds] -format %Y.%m.%d]
	foreach {year month day} [split $today .] {break}
	set month monthAbbreviation($month)
	regsub {^0} $day {} day
	set todayDate [subst [subst [subst $accessDate]]]
# Compute the todayDate - end

# Compute siteList
#	set siteList [list $serverAddressWithIP]
	set siteList [list $serverAddress]
# Compute siteList - end

# puts $siteList

# Compute the smallerFirstDay
	set query "list GetFirstDay $rep"
# MULTIPLE SUBMIT
	set searchResultList {}
	MultipleSubmit {} $query searchResultList 0 $siteList
	set searchResultList [join $searchResultList]
	set numberOfActiveSites $numberOfSatisfiedQueries
	set smallerFirstDay $today

# LOOP OVER EACH SITE (now just one loop)
	foreach {site firstDay} $searchResultList {
# site not used
		if {$firstDay == ""} {continue}
		set smallerFirstDay [StringMin $smallerFirstDay $firstDay]
	}
# Compute the smallerFirstDay - end

	puts [SetFont [subst [set ${languageRep2}::header]]]

	if {$smallerFirstDay != ""} {
# at least on click
# Compute periodLength
		set firstAccessNOD [ComputeNOD $smallerFirstDay]
		set todayNOD [ComputeNOD $today]
		set allPeriod [expr $todayNOD - $firstAccessNOD + 1]
		set periodLength [expr $allPeriod / 10]	;# integer part
# Compute periodLength - end

		if {$periodLength != 0} {
# Compute histogramSum and totalNumberOfVisits
# startingDay
			set numberOfDays [expr $periodLength * 10]
			set startDayNOD [expr $todayNOD - $numberOfDays + 1]
			set startDay [clock format [expr $startDayNOD * 24 * 3600] -format %Y.%m.%d]
			foreach {year month day} [split $startDay .] {break}
			set month monthAbbreviation($month)
			regsub {^0} $day {} day
			set startingDay [subst [subst [subst $accessDate]]]

			set may17NOD [ComputeNOD 2015.05.17]	;# date of the new count policy
			set oldCountPolicyPeriod [expr $may17NOD - $startDayNOD]
			if {$oldCountPolicyPeriod > 0} {
				set periodNumber [expr 1 + ($oldCountPolicyPeriod - 1) / $periodLength]	;# 1, 2, 3...
			} else {
				set periodNumber 0
			}
			
# LOOP OVER EACH SITE (now just one loop)
			foreach i {1 2 3 4 5 6 7 8 9 10} {
				set histogramSum($i) 0
			}
			set totalNumberOfVisits 0
# puts --$searchResultList--
			foreach {site firstDay} $searchResultList {
# firstDay not used
				foreach {serverName urlibPort} [ReturnCommunicationAddress $site] {break}
				if [catch \
				{StartCommunication $serverName $urlibPort} \
				localURLibClientSocketId] {continue}	;# catch is for unix
# histogram
catch {
				array set histogram [Submit $localURLibClientSocketId [list GetHistogram $rep $periodLength $todayNOD] 0]	;# not async
} m
				close $localURLibClientSocketId
# puts $m
# global errorInfo
# puts $errorInfo
				foreach i {1 2 3 4 5 6 7 8 9 10} {
					set histogramSum($i) [expr $histogram($i) + $histogramSum($i)]
					set totalNumberOfVisits [expr $histogram($i) + $totalNumberOfVisits]
				}
			}
# Compute histogramSum and totalNumberOfVisits - end
		} else {
# Compute totalNumberOfVisits
# startingDay
			foreach {year month day} [split $smallerFirstDay .] {break}
			set month monthAbbreviation($month)
			regsub {^0} $day {} day
			set startingDay [subst [subst [subst $accessDate]]]

# LOOP OVER EACH SITE (now just one loop)
			set totalNumberOfVisits 0
			foreach {site firstDay} $searchResultList {
# firstDay not used
				foreach {serverName urlibPort} [ReturnCommunicationAddress $site] {break}
				if [catch {StartCommunication $serverName $urlibPort} localURLibClientSocketId] {continue}	;# catch is for unix
# numberOfVisits
				set numberOfVisits [Submit $localURLibClientSocketId [list GetNumberOfVisits $rep] 0]	;# not async
				close $localURLibClientSocketId
				set totalNumberOfVisits [expr $numberOfVisits + $totalNumberOfVisits]
			}
# Compute totalNumberOfVisits - end
		}
		puts [subst [set ${languageRep2}::atLeastOneClick]]
		if {$periodLength != 0} {
# Draw the histogram
# Find the vertical scale
			set max 0
			foreach i {1 2 3 4 5 6 7 8 9 10} {
				set max [Max $max $histogramSum($i)] 
			}
			if {$max == 0} {
				set maxHeight 0
				set max 1	;# to avoid division by zero
			} else {
				set maxAverage [expr $max. / $periodLength]
				set maxHeight \
					[expr int ([expr [expr 4 + log10($maxAverage)] * 10])]
			}
# Find the vertical scale - end

# Compute precision
			set precision [expr int([expr ceil([expr log10($periodLength)])])]
			if {$precision > 2} {set precision 2}
			set precisionAll [expr int([expr ceil([expr log10($allPeriod)])])]
			if {$precisionAll > 2} {set precisionAll 2}
			foreach i {1 2 3 4 5 6 7 8 9 10} {
				set counter($i) 0
			}
# Compute precision - end

# average
			set average [format "%4.${precisionAll}f" \
				[expr $totalNumberOfVisits. / $numberOfDays]]
			lappend page {<TABLE BORDER=1 ALIGN=CENTER>}
			lappend page {<TR BGCOLOR=#ffffcc>}
			lappend page {<TD ALIGN=CENTER>${Average number of visits per day}<BR>}
			lappend page "<FONT SIZE=1>${over 10 periods of $periodLength days}</FONT></TD></TR>"
			lappend page {<TR><TD><TABLE BORDER=0 CELLSPACING=1 CELLPADDING=0>}
			lappend page {<TR VALIGN=BOTTOM BGCOLOR=#eeeeee>}
			foreach i {1 2 3 4 5 6 7 8 9 10} {
				set height [expr $histogramSum($i) * $maxHeight / $max]
				if {$height == 0} {
					lappend page "<td align=center>\
<img src=../image/dot_transparent.gif height=8 width=1><br>\
<font size=-2>$histogramSum($i)</font><br>\
<img src=../image/dot_transparent.gif height=1 width=32><BR>\
<img src=../image/dot_transparent.gif height=6 width=44></td>"
				} else {
					set localAverage [format "%4.${precision}f" \
[expr $histogramSum($i). / $periodLength]]
					lappend page "<td align=center>\
<img src=../image/dot_transparent.gif height=8 width=1><br>\
<font size=-2>$localAverage</font><br>\
<img src=../image/dot_purple.gif height=$height width=32><BR>\
<img src=../image/dot_transparent.gif height=6 width=44></td>"
				}
			}
			lappend page {</TR>}
			lappend page {<tr BGCOLOR=#cccccc><td align=center>\
<img src=../image/dot_darkgreen.gif align=top width=2 height=22><img src=../image/dot_darkgreen.gif align=top width=2 height=6>\
&nbsp;&nbsp;<font size=1 [expr $periodNumber == 1?{color=brown}:{}]>1</font>&nbsp;&nbsp;&nbsp;&nbsp;</td>}
			foreach i {2 3 4 5 6 7 8 9} {
				lappend page "<td align=center>\
<img src=../image/dot_transparent.gif width=1 height=14>\
&nbsp;&nbsp;<font size=1 [expr $periodNumber == $i?{color=brown}:{}]>$i</font>&nbsp;&nbsp;&nbsp;</td>"
			}
			lappend page {<td align=center>\
&nbsp;&nbsp;&nbsp;<font size=1 [expr $periodNumber == 10?{color=brown}:{}]>10</font>&nbsp;&nbsp;\
<img src=../image/dot_darkgreen.gif align=top width=2 height=6><img src=../image/dot_darkgreen.gif align=top width=2 height=22></td></tr>\
</table></td></tr></table></P>}
			lappend page {<P ALIGN=CENTER>}
			if {$periodNumber != 0} {lappend page "${The red period number indicates that the corresponding period contains the day May 17, 2015<sup>1</sup>.}<BR>"}
			lappend page {
${The height of each purple bar is proportional to the average\
number of visits per day<BR>within the corresponding period.}<BR>}
			lappend page "${Period 1 begins on $startingDay} ( \
<img src=../image/dot_darkgreen.gif align=top width=2 height=18><img src=../image/dot_darkgreen.gif align=top width=2 height=4> ),"
			lappend page "${and Period 10 ends on $todayDate} ( \
<img src=../image/dot_darkgreen.gif align=top width=2 height=4><img src=../image/dot_darkgreen.gif align=top width=2 height=18> ).<BR>"
			lappend page "${The number of visits over the 10 periods is \
<B>$totalNumberOfVisits</B>.}<BR>"
			lappend page "${The average number of visits per day over the 10 periods is \
<B>$average</B>.}<BR>"
			lappend page "${<sup>1</sup>Before May 17, 2015, all each user visits (IP) were added, thereafter, \
only one visit per day for each user (IP) is added.}<BR>"
			if {$numberOfSites != 1} {
				lappend page "${These statistics have been extracted from $numberOfActiveSites \
out of $numberOfSites sites.}</P>"
			}
			puts [subst [join $page \n]]
# Draw the histogram - end
		}
	} else {
# no click
		puts [set ${languageRep2}::noClick]
	}
	set display [GetFrameName]
	puts [CreateReturnButton <HR> ../$col/$languageRep2/doc/mirror {} $display $Return {} {} {} {} 1]
	puts $fontTag2</TD></TR></TABLE></BODY></HTML>
}
