<?php
/*
* track.php
* http://tasuke.dna.affrc.go.jp/
*
* Author: Ryutaro Itoh
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences   
*
* This software is released under the MIT License.
*
* http://opensource.org/licenses/mit-license.php
*/

require '../conf/config.php';
require './common.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");
if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$prm_Zoom)) {
	$prm_Zoom = "1k";
}
if(!_validate_chrs($conn,$prm_Chr)){_stopError("||Invalid value");}
$prm_Pos = (int)$prm_Pos;
$prm_Block = (int)$prm_Block;
for($i=0;$i<count($prm_Tracks);$i++) {
	if(!_validate_each_tracks($conn,$prm_Tracks[$i]) && $prm_Tracks[$i] != "Primer3 Result"){_stopError("||Invalid value");}
}
$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, others 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";
$rtnString="";

$stmt = $conn->stmt_init();
$stmt->prepare($query);
$stmtSub = $conn->stmt_init();
$stmtSub->prepare($subquery);
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,$rowN6);

    $a1=0;
    $a2=0;
    $a3=0;
    $rtnArr=array();
    while ($stmt->fetch()) {
        $dest_url=$rowN0;
        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;
        }
        if($external_link_tag_gff != "ID" and $external_link_tag_gff != ""){
            $str_array = explode(";",$rowN6);
            for ($a=0; $a<count($str_array); $a++){
                $tag_val = explode("=",$str_array[$a]);
                if($tag_val[0]==$external_link_tag_gff){
                    $dest_url=$tag_val[1];
                    break;
                }else{
                    $dest_url="";
                }
            }
        }
      
        $arrStr="{\"id\":\"".$rowN0."\",\"name\":\"".$rowN1."\",\"pos\":\"".(int)$rowN2."\",\"length\":\"".(int)$rowN4."\",\"strand\":\"".$rowN5."\",\"s\":\"".$p1."\",\"e\":\"".$p."\",\"h\":\"".$h."\",\"rs\":\"".$rs."\",\"re\":\"".$re."\",\"ln\":\"".$dest_url."\"";
        $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 _stopError($str){
    echo $str;
    exit;
}

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;
}

function _validate_chrs($conn, $prm_Chr){
    $flag = false;
    $query = "select seq from sys_chromosome where id=? limit 1";
    $stmt = $conn->stmt_init();
    $stmt->prepare($query);
    $stmt->bind_param("s", $prm_Chr);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($row0);
    while ($stmt->fetch()) {
        $flag = true;
    }
    $stmt->free_result();
    $stmt->close();
    if($flag){
       return true;
    }else{
       return false;
    }
}

function _validate_each_tracks($conn,$list){
	$flag = false;
	$query = "SELECT track FROM sys_track where track = ? limit 1";
        $stmt = $conn->stmt_init();
        $stmt->prepare($query);
        $stmt->bind_param("s", $list);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($row0);
        while ($stmt->fetch()) {
            $flag = true;
        }
        $stmt->free_result();
        $stmt->close();
        if($flag){
           return true;
        }else{
           return false;
        }
}
?>

