<?php // diaMeter.php - construct indicators
// ------------------------------------------------------------------------
// Copyright (c) 2005, 2006, 2015 Denis Guinnepain
 
// ------------------------------------------------------------------------
// This file is part of Diamentis

// Diamentis is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

// Diamentis is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with phpBugTracker; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ------------------------------------------------------------------------

require_once('include.php');
$DiaMeter="fee";

function show_stat($build_sql_query,$statField, $weightField, $verbose)
{
//print("debut show_stat\n");
	global $db;
	$result_ids = array();
	$fileCount = 0;
	$count_sql = "";
	$grouped_sql = "";
	$table_j1="";
	$weightField="f.$weightField";
//println("query");
//printarray($build_sql_query);
	// type of the ordered field
	$type_sql = "SELECT field_type_title, field_conf_id, properties FROM " . TBL_FIELD_TYPE . " ft, " . TBL_FIELD_CONF . " fc WHERE ft.field_type_id=fc.field_type_id AND fc.field_name=\"$statField\"" ;
	$res =  $db->getRow($type_sql);
	$stat_type=$res['field_type_title'];
	$stat_id=$res['field_conf_id'];
	$stat_properties=$res['properties'];
	//print "type : $stat_type <br> id : $stat_id <br> properties : $stat_properties"; 

	$doJoin = false;
	// some special fields are ordered differently
	switch($statField) 
	{
		case 'project_id' :
			$join_table=TBL_PROJECT;
			$field_readable="project_id";
			$group_select=$statField;
			$group_value="jt.project_name";
			$order_value="jt.project_name";
			$doJoin = true;
			$table_j1="fi";
			break;
		case 'assigned_to' :
			$join_table=TBL_ASSIGNATION . " asst, " . TBL_AUTH_USER;
			$field_readable="user_id";
			$group_select="user_id and asst.file_id = f.bug_id";
			$group_value=db_concat(" jt.first_name ", "\" \"", " jt.last_name ");
			$order_value=$group_value;
			$doJoin = true;
			$table_j1="asst";
			break;
		default :
			switch ($stat_type) 
			{
				case SELECT_TWINBOX_TYPE : 
					$sp = new MPSubProperty($stat_properties);
					if (isset($sp->SB_twin_id)) 
			 		{
						$stat_id=$sp->SB_twin_id;
						$stat_id = intval($stat_id);
					}
				case SELECTBOX_TYPE :
					if ($stat_id==22 || $stat_id==23) //modified_by and created_by
					{
						$join_table=TBL_AUTH_USER;
						$field_readable="user_id";
						$group_select=$statField;
						$group_value=db_concat(" jt.first_name ", "\" \"", " jt.last_name ");
						$order_value=$group_value;
						$doJoin = true;
						$table_j1="f";
					}
					else
					{
						$join_table=TBL_SELECTBOX_VALUE;
						$field_readable="sv_id";
						$group_select=$statField;
						$group_value="jt.sv_value";
						$order_value="jt.sv_order";
						$doJoin = true;
						$table_j1="f";
					}
					break;
				case TIMESTAMP_TYPE :
					$doJoin = false;
					$group_value="DATE_FORMAT( FROM_UNIXTIME($statField), ' %x FW %v' )";
					$order_value=$statField;
					break;
				default :
					$doJoin = false;
					$group_value=$statField;
					$order_value=$statField;
					break;
			}
			break;
	}
		

	if (is_string($build_sql_query)) 
	{
		$build_sql_query = array($build_sql_query);
	}

	
	//printarray($build_sql_query); 
	foreach($build_sql_query as $sql) 
	{
//		println("la build_sql_query vaut $build_sql_query");
		if ($grouped_sql=="")
		{
			if ($doJoin)
			{
				$sql = preg_replace('/FROM/i', "FROM $join_table jt,", $sql);
				$sql = preg_replace('/SELECT .* FROM/i', "SELECT $group_value as label, $weightField as _weight, $order_value as _order FROM ", $sql);
				$sql .= " AND jt.$field_readable = $table_j1.$group_select"; 
			}
			else
			{
				$sql = preg_replace('/SELECT .* FROM/i', "SELECT $group_value as label, $weightField as _weight, $order_value as _order FROM ", $sql);
			}
			$grouped_sql = "$sql ";
			$isMultiProject = false;
		}
		else
		{
			if ($doJoin)
			{
				$sql = preg_replace('/FROM/i', "FROM $join_table jt,", $sql);
				//$sql = preg_replace('/SELECT /i', "SELECT $order_value, COUNT($order_value)", $sql);
				$sql = preg_replace('/SELECT .* FROM/i', "SELECT $group_value as label, $weightField as _weight, $order_value as _order FROM ", $sql);
				$sql .= " AND jt.$field_readable = $table_j1.$group_select"; 
			}
			else
			{
				$sql = preg_replace('/SELECT .* FROM/i', "SELECT $group_value as label, $weightField as _weight, $order_value as _order FROM ", $sql);
			}
			$grouped_sql .= " UNION ALL $sql ";
			$isMultiProject = true;
		}
	}

	$grouped_sql =  "SELECT label, count(*) as data, SUM(_weight) as w_data, _order  FROM ($grouped_sql) AS tmpTable GROUP BY label ORDER BY _order";
	$res = $db->getAll($grouped_sql);
//println("la requete vaut : $grouped_sql");
	if ($stat_type==TIMESTAMP_TYPE)
	{
		foreach ( $res as $k => $v )
		{
			$read_week=$v['_order'];
			$label_ref=$v['label'];
			if ($k==0)
			{
				$expected_week  = $read_week;
				if (intval(date("m",$expected_week))==12 && intval(date("W",$expected_week))==1)
				{
					$label=" " . date("Y",$expected_week)+1 . " FW " . date("W",$expected_week);
				}
				else
				{
					$label=" " . date("Y",$expected_week) . " FW " . date("W",$expected_week);
				}
			}
			//println("label_ref{$label_ref}label{$label}na$k ");
			while ($read_week>$expected_week  && strcmp($label_ref,$label)>0)
//				&& intval(date("Y",$read_week))>=intval(date("Y",$expected_week)) 
//				&& intval(date("W",$read_week))>intval(date("W",$expected_week)))
			{
				//println(  " read_week : " . $read_week . " " . date("Y",$read_week) . " FW " . date("W",$read_week) . " expected_week : " . $expected_week . " " . date("Y",$expected_week) ." FW " . date("W",$expected_week) . " date " . date("F j, Y, g:i a",$expected_week));
				//println("$label");
				//printarray(array('_order'=>$expected_week ,'label'=>$label,'data'=>0,'w_data'=>0));
				$res2[]=array('_order'=>$expected_week ,'label'=>$label,'data'=>0,'w_data'=>0);
				$expected_week  +=604800; // +1 week
				if (intval(date("m",$expected_week))==12 && intval(date("W",$expected_week))==1)
				{
					$label=" " . date("Y",$expected_week)+1 . " FW " . date("W",$expected_week);
				}
				else
				{
					$label=" " . date("Y",$expected_week) . " FW " . date("W",$expected_week);
				}
			}
			//println("$label ($expected_week)" );
			$res2[]=$v;
			$expected_week  +=604800; // +1 week
			if (intval(date("m",$expected_week))==12 && intval(date("W",$expected_week))==1)
			{
				$label=" " . date("Y",$expected_week)+1 . " FW " . date("W",$expected_week);
			}
			else
			{
				$label=" " . date("Y",$expected_week) . " FW " . date("W",$expected_week);
			}
		}
		//printarray($res2);
		return $res2 ;
	}
	return $res;

}


function extract_data($fc_id,$prj_id,$restricted_projects) {
	global $db;
	// Grab the legend
	$rs = $db->query("select sv_id, sv_value from ".TBL_SELECTBOX_VALUE." WHERE field_conf_id=$fc_id ORDER BY sv_order");
	while ($rs->fetchInto($row)) {
		$stats[$row['sv_id']]['name'] = $row['sv_value'];
		$stats[$row['sv_id']]['count'] = 0;
//printarray($row);
	}
	$field_name=$db->getOne($toto="SELECT field_name FROM " . TBL_FIELD_CONF . " WHERE field_conf_id=$fc_id");
//print "extract_data : $toto et $field_name";
	// Grab the data
	$rs = $db->query("select fp.$field_name as field_id, count(fp.$field_name) as count from ".TBL_PREFIX.
		"file_prj_id_$prj_id fp group by fp.$field_name");
	while ($rs->fetchInto($row)) {
			$stats[$row['field_id']]['count'] = $row['count'];
	}
	return $stats;
}

/**
 * burntChart()
 * Personal implementation of array_diff_key().
 * Return an array of the array1 elements whose index value is not in array2 index values
 * I did it because it doesn't exist in my version of PHP
 * If a parameter isn't an array : return null
 * 
 * @param  $filelist file list to be burnt
 * @param  $field_id file reference to be tracked : it shall be an integer
 * @param  $interval define the sample period for the tracking
 * @param  $initial_Date define the 0 absciss for the chart
 * @param  $end_Date determine the date when Y axis shall be at 0
 * @return none
 */
function burntChart($filelist,$field_id, $interval, $initial_Date, $end_Date, $verbose)
{

}


//$fc_id=24;
//$field_name="field_24";
//$tblFileProject='mplus_file_prj_id_3';

//$rs = $db->query("SELECT sbv.sv_value, " .
//		db_concat("', SUM(CASE WHEN sbv1.sv_id = '", 'sbv.sv_id',"' THEN 1 ELSE 0 END) AS \"'",'sbv.sv_value', "'\"' ") . " FROM " . TBL_SELECTBOX_VALUE . " sbv WHERE field_conf_id=$fc_id ORDER BY sv_order");
//
//	//$querystring = 'SELECT sbv2.sv_value AS "Data2" ';
//	$querystring = "SELECT 12 ";

//	while (list($fieldtitle, $countquery) = $rs->fetchRow(DB_FETCHMODE_ORDERED)) {
//		$resfields[] = $fieldtitle;
//		$querystring .= $countquery;
//	}
//	$resfields[] = 'Total';
//
//	$sql=$querystring . " , count(fp.bug_id) FROM " .$tblFileProject . " fp, " . TBL_SELECTBOX_VALUE . " sbv1  WHERE sbv1.field_conf_id=$fc_id AND sbv1.sv_id=fp.$field_name ";
//	println("SQL vaut : $sql");
//	$res=$db->getAll($sql);
//	printarray($res);

//printarray(extract_data('24','3',Null));




//die;
	




//	$sql=$querystring . " , count(fp.file_id) FROM " .$tblFileProject . " fp, " . TBL_SELECTBOX_VALUE . " sbv1, " . TBL_SELECTBOX_VALUE . " sbv2, " . TBL_FIELD_CONF . " fc, WHERE sbv2.fieldconf_id=fc.fieldconf_id AND fc.field_name=fp.$field_name  group by fp.$fieldname order by sbv2.sv_value";

?>
