<?php

  require '../conf/config.php';

  ////////////////////////////////// Connecting with DB
  if( !$conn = new mysqli($host, $user, $pswd, $db)) {
    error_log("Connection failed.\n");
    exit;
  }

  ////////////////////////////////// Parameters
  $prm_Tracks=array();
  (isset($_GET['prm_Zoom']) && !empty($_GET['prm_Zoom'])) ? $prm_Zoom=$_GET['prm_Zoom']:returnError("Error");
  (isset($_GET['prm_Chr']) && !empty($_GET['prm_Chr'])) ? $prm_Chr=$_GET['prm_Chr']:returnError("Error");
  (isset($_GET['prm_Pos']) && !empty($_GET['prm_Pos'])) ? $prm_Pos=$_GET['prm_Pos']:returnError("Error");
  (isset($_GET['prm_Block']) && !empty($_GET['prm_Block'])) ? $prm_Block=$_GET['prm_Block'] : returnError("Error");
  (isset($_GET['prm_Tracks']) && !empty($_GET['prm_Tracks'])) ? $prm_Tracks=$_GET['prm_Tracks'] : returnError("Error");

  $db_range_start=$prm_Pos*_cvtZoom($prm_Zoom)-_cvtZoom($prm_Zoom);
  $db_range_end=($prm_Pos+$prm_Block)*_cvtZoom($prm_Zoom);

  ///////////////////////////////////////////////////////////////////////////////
  // Tracks
  ///////////////////////////////////////////////////////////////////////////////
  
  $query = "SELECT id,name,pos,end+1,(end-pos+1),strand FROM sys_track WHERE track= ? and chr= ? and parent=1 and end+1 > ? and pos < ? order by pos";
  $subquery = "SELECT pos, (end-pos+1), type from sys_track where track= ? and id= ? and parent=0 order by pos";
  
  $stmt = $conn->stmt_init();
  $stmt->prepare($query);
  $stmtSub = $conn->stmt_init();
  $stmtSub->prepare($subquery);
  
  $rtnString="";
  for($i=0;$i<count($prm_Tracks);$i++) {
    $stmt->bind_param("ssii", $prm_Tracks[$i], $prm_Chr, $db_range_start, $db_range_end);  
	$stmt->execute();
	$stmt->store_result();
	$stmt->bind_result($rowN0,$rowN1,$rowN2,$rowN3,$rowN4,$rowN5);
	
	$a1=0;
    $a2=0;
    $a3=0;
    $rtnArr=array();
    while ($stmt->fetch()) {
		
		if ( $prm_Zoom == "1b" ) {
			$rs=((int)$rowN2/_cvtZoom($prm_Zoom))-$prm_Pos;
			$re=((int)$rowN3/_cvtZoom($prm_Zoom))-$prm_Pos;
			$p1=(int)((int)$rowN2/_cvtZoom($prm_Zoom))-$prm_Pos;
			if ((int)$rowN3%_cvtZoom($prm_Zoom)){
				$p=(int)((int)$rowN3/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			} else {
				$p=(int)((int)$rowN3/_cvtZoom($prm_Zoom))-$prm_Pos;
			}
		}
		else{ 
			$rs=((int)$rowN2/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			$re=((int)$rowN3/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			$p1=(int)((int)$rowN2/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			if ((int)$rowN3%_cvtZoom($prm_Zoom)){
				$p=(int)((int)$rowN3/_cvtZoom($prm_Zoom))-$prm_Pos+2;
			} else {
			$p=(int)((int)$rowN3/_cvtZoom($prm_Zoom))-$prm_Pos+1;
			}
		}
      
      if ( $p1 > $a1 || $a1 == null ) {
        $h=1;
        $a1=$p;
      } else if ( $p1 > $a2 || $a2 == null ) {
        $h=2;
        $a2=$p;
      } else if ( $p1 > $a3 || $a3 == null ) {
        $h=3;
        $a3=$p;
      } else {
        $h=4;
      }
	  $arrStr="{\"id\":\"".$rowN0."\",\"name\":\"".$rowN1."\",\"pos\":\"".(int)$rowN2."\",\"length\":\"".(int)$rowN4."\",\"strand\":\"".$rowN5."\",\"s\":\"".$p1."\",\"e\":\"".$p."\",\"h\":\"".$h."\",\"rs\":\"".$rs."\",\"re\":\"".$re."\"";
      $idsArr=array();
      if ( $rowN0 != "" ) {
        $stmtSub->bind_param("ss", $prm_Tracks[$i], $rowN0);  
		$stmtSub->execute();
		$stmtSub->store_result();
		$stmtSub->bind_result($rowS0,$rowS1,$rowS2);

        while ($stmtSub->fetch()) {
          $s=($rowS0-$rowN2)/$rowN4*100;
          $l=$rowS1/$rowN4*100;
          if ( strstr(strtolower($rowS2), "utr") ) {$t="u";}
          else if ( strstr(strtolower($rowS2), "cds") ) {$t="c";}
          else {$t="a";}
          $idsArr[]=$t."-".$s."-".$l;
        }
		$stmtSub->free_result();
      }

	  $subStr="";
      if ( count($idsArr) ) {
        $subStr=",\"t\":\"";
        for($j=0;$j<count($idsArr);$j++){
          $subStr=$subStr.$idsArr[$j];
          if($j<count($idsArr)-1){$subStr=$subStr.";";}
        }
        $subStr=$subStr."\"";
      }

      $arrStr=$arrStr.$subStr."}";
      $rtnArr[]=$arrStr;
    }
	
	$stmt->free_result();
    
	$rtnString=$rtnString."[";
    for($j=0;$j<count($rtnArr);$j++){
      $rtnString=$rtnString.$rtnArr[$j];
      if($j<count($rtnArr)-1){$rtnString=$rtnString.",";}
    }
    $rtnString=$rtnString."]";

    if($i<count($prm_Tracks)-1){$rtnString=$rtnString."|";}

  }
   $stmt->close();
   $stmtSub->close();

  ///////////////////////////////////////////////////////////////////////////////
  // Loading FASTA during zoom is '1b'
  ///////////////////////////////////////////////////////////////////////////////
  
  if ( $prm_Zoom == '1b' ) {
    $prm_Chr = $conn->real_escape_string($prm_Chr);
	$queryFa = "SELECT ".$prm_Chr."_f FROM sys_fasta WHERE pos>=? AND pos<? ";
	$stmtFa = $conn->stmt_init();
	$stmtFa->prepare($queryFa);
	$paramFa1=($prm_Pos+$prm_Block);
	$stmtFa->bind_param("ii", $prm_Pos, $paramFa1);  
	$stmtFa->execute();
	$stmtFa->store_result();
	$stmtFa->bind_result($rowF0);
    while ($stmtFa->fetch()) {
      $arrF[]="{\"f\":\"".$rowF0."\"}";
    }
	$stmtFa->free_result();
	$stmtFa->close();
	
    $rtnString=$rtnString."|[";
    for($i=0;$i<count($arrF);$i++){
      $rtnString=$rtnString.$arrF[$i];
      if($i<count($arrF)-1){$rtnString=$rtnString.",";}
    }
    $rtnString=$rtnString."]";
  } else {
    $rtnString=$rtnString."|[]";
  }

  mysqli_close($conn);
  echo $rtnString;
  
  function returnError($str){
    echo $str;
  }

  function _cvtZoom($str) {
    preg_match("/^[0-9]+/", $str, $r1);
    preg_match('/[b,k]$/', $str, $r2);
    $v=$r1[0];
    if($r2[0] == "b"){
      $r=1*(int)$v;
    } else {
      $r=1000*(int)$v;
    }
    return (int)$r;
  }

?>

