<?php
require_once '../conf/config.php';

function getSerialTableByColumn($conn, $db, $namebase, $colname) {
	global $autoDetectSerialTable;

	if(empty($autoDetectSerialTable) || $autoDetectSerialTable == 0) return $namebase;  

	$tables = getTableSet($conn, $db, $namebase);
	$numTables = count($tables);
	if($numTables == 1) {
		return $tables[0];
	} else if($numTables == 0) {
		return $namebase;
	}
	$targetTable = $namebase;
	foreach ($tables as $table) {
		if(existColumn($conn, $db, $table, $colname)) {
			$targetTable = $table;
			break;
		}
	}
//error_log("Table:". $namebase. " => ". $targetTable);
	return $targetTable;
}
function getTableSet($conn, $db, $namebase) {
	$sql = "SHOW TABLES ";
	if(!empty($db)) $sql .= "FROM ". $db. " ";
	$sql .= "like '". $namebase. "%'";
	$stmt = $conn->stmt_init();
	$stmt->prepare($sql);
	$stmt->execute();
	$stmt->store_result();
	$stmt->bind_result($tablename);
	$tables = array();
	while ($stmt->fetch()) {
//		error_log("Table:". $tablename);
		if($tablename == $namebase) {
			$tables = array($tablename);
			break;
		} else if(preg_match("/^". $namebase."\d+$/", $tablename)) {
			$tables[] = $tablename;
		}
	}
	//error_log(print_r($tables, TRUE));
	$stmt->close();
	return $tables;
}
function existColumn($conn, $db, $tablename, $colname) {
	$sql = "SHOW COLUMNS FROM ".  $tablename. " ";
	if(!empty($db)) $sql .= "FROM ". $db. " ";
	$sql .= "LIKE '". $colname. "'";
	$stmt = $conn->stmt_init();
	$stmt->prepare($sql);
	$stmt->execute();
	$stmt->store_result();
	$stmt->bind_result($col, $type, $null, $key, $def, $ext);
	$exist = FALSE;
//	while($stmt->fetch()) {
//		error_log("Col:". $col);
//	}
	if ($stmt->fetch()) $exist = TRUE;
	$stmt->close();
	return $exist;
}
function getCDSLength($conn, $prm_obj_id) {
  $cdslen = 0;
  $query = "select pos,end from sys_track where id=? and (type='CDS' or type='cds') order by pos";
  $stmt = $conn->stmt_init();
  $stmt->prepare($query);
  $stmt->bind_param("s", $prm_obj_id);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($row0,$row1);
  while ($stmt->fetch()) {
      $cdspart = ($row1-$row0+1);
      $cdslen = $cdslen + $cdspart;
  }
  $stmt->free_result();
  $stmt->close();
  return $cdslen;
}
?>
