<?php
/*
* info.php
* http://tasuke.dna.affrc.go.jp/
*
* Author: Ryutaro Itoh
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences   
*
*/

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

//////////////////////////////////  Paramenters
(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_Mode']) && !empty($_GET['prm_Mode'])) ? $prm_Mode=$_GET['prm_Mode']:returnError("Error");
(isset($_GET['prm_Pos']) && !empty($_GET['prm_Pos'])) ? $prm_Pos=$_GET['prm_Pos']:returnError("Error");
(isset($_GET['prm_QUAL']) && !empty($_GET['prm_QUAL'])) ? $prm_QUAL=$_GET['prm_QUAL']:returnError("Error");
(isset($_GET['prm_DP']) && !empty($_GET['prm_DP'])) ? $prm_DP=$_GET['prm_DP']:returnError("Error");
(isset($_GET['prm_DP4']) && !empty($_GET['prm_DP4'])) ? $prm_DP4=$_GET['prm_DP4']:returnError("Error");
(isset($_GET['prm_Acc']) && !empty($_GET['prm_Acc'])) ? $prm_Acc=$_GET['prm_Acc'] : returnError("Error");
$enabledEffImpacts = array("0" => True, "1" => True, "2" => True, "3" => True, "-1" => True);
if(isset($_GET['prm_EffGrps']) && !empty($_GET['prm_EffGrps'])) {
        try {
                $impacts = json_decode($_GET['prm_EffGrps']);
                _setSnpEffImpactFilterMap($enabledEffImpacts, $impacts);	// Do not use return value(boolean)
        } catch ( Exception $ex ) {}
}
///Validating///
if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$prm_Zoom)) {
        $prm_Zoom = "1k";
}
if(!_validate_chrs($conn,$prm_Chr)){exit;}
if(preg_match("/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/",$prm_Mode)) {
        $prm_Mode = "s";
}
$prm_Pos = (int)$prm_Pos;
$prm_QUAL = (int)$prm_QUAL;
$prm_DP = (int)$prm_DP;
$prm_DP4 = (int)$prm_DP4;
list($zoom_v,$zoom_r,$zoom_chr)=_cvtZoom($prm_Zoom, $prm_Chr);
$prm_Acc = $conn->real_escape_string($prm_Acc);
$query="";

//$EFFMAP = array('MODIFIER' => 0, 'LOW' => 1, 'MODERATE' => 2, 'HIGH' => 3);                

if ( $prm_Mode == "dp+s" || $prm_Mode == "s" ) {
    $query = "SELECT pos,variant,REF,ALT,EFF,GT,QUAL FROM ".$prm_Acc."_variant WHERE chr= ? and pos>? and pos<=? and QUAL>=? and DP>=? and (DP3+DP4)>=? and variant='s' ";
} else if ( $prm_Mode == "dp+i" || $prm_Mode == "i" ) {
    $query = "SELECT pos,variant,REF,ALT,EFF,GT,QUAL FROM ".$prm_Acc."_variant WHERE chr= ? and pos>? and pos<=? and QUAL>=? and DP>=? and (DP3+DP4)>=? and variant != 's' ";
} else if ( $prm_Mode == "dp" ) {
    $query = "SELECT pos,variant,REF,ALT,EFF,GT,QUAL FROM ".$prm_Acc."_variant WHERE chr= ? and pos>? and pos<=? and QUAL>=? and DP>=? and (DP3+DP4)>=? and variant = 'dp' ";
} else{
    $query = "SELECT pos,variant,REF,ALT,EFF,GT,QUAL FROM ".$prm_Acc."_variant WHERE chr= ? and pos > ? and pos <= ? and QUAL >= ? and DP>= ? and (DP3+DP4) >= ? ";
}
$query_eff="SELECT eff_grp FROM sys_snpEff WHERE eff_name like ? ";
////////////////////////////////////////////////// Range
$e=$zoom_v*$zoom_r*$prm_Pos;
$s=$e-$zoom_v*$zoom_r;

////////////////////////////////////////////////// SQL
$datas = array();
$stmt_eff = $conn->stmt_init();
$stmt_eff->prepare($query_eff);
$stmt = $conn->stmt_init();
$stmt->prepare($query);
$stmt->bind_param("siiiii", $prm_Chr, $s, $e, $prm_QUAL, $prm_DP, $prm_DP4); 
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($row0,$row1,$row2,$row3,$row4,$row5,$row6);
while ($stmt->fetch()) {
    if ( $row1 == "s" ) $varType="SNP";
    if ( $row1 == "i" ) $varType="INS";
    if ( $row1 == "d" ) $varType="DEL";
    $each_effect=array();
    $eff_list=explode(",", $row4);
    $ret_eff=array();
    $t=count($eff_list);

    $validVariant = False;
    if($enabledEffImpacts{"-1"} && empty($row4)) $validVariant = True;

    for($i=0; $i<$t; $i++){
	$effInfo = _parseSnpEff($eff_list[$i]);
	$impact = $effInfo["impactc"];
/*
	$impact = "";
	if(preg_match("/^[^\|]+\((.+)$/", $eff_list[$i], $matches)) {
		// EFF
		$EffInfo = explode("|", $matches[1]);
		$impact = $EFFMAP{$EffInfo[0]};
	} else {
		// ANN
                $effect=explode("|", $eff_list[$i]);
		$impact = $EFFMAP{$effect[2]};
	}
*/
	if(!$enabledEffImpacts{(string)$impact}) continue;
	$validVariant = True;

	$ret_eff[] = $eff_list[$i]."|". $impact;
    }
    if($validVariant) $datas[]="{\"pos\":\"".$row0."\",\"variant\":\"".$varType."\",\"ref\":\"".$row2."\",".
              "\"alt\":\"".$row3."\",\"eff\":\"".implode(",", $ret_eff)."\",\"gt\":\"".$row5."\",\"qual\":\"".$row6."\"}";
}
$stmt->free_result();
$stmt->close();
$stmt_eff->close();
mysqli_close($conn);
$rtnString="[";
for ($i=0; $i<count($datas); $i++) {
    $rtnString=$rtnString.$datas[$i];
    if ( $i<count($datas)-1 ) $rtnString=$rtnString.",";
}
$rtnString=$rtnString."]";
echo $rtnString;
exit;


////////////////////////////////////////////////// functions
function returnError($str){
    echo $str;
}

function _cvtZoom($str1, $str2) {
    preg_match("/^[0-9]+/", $str1, $r1);
    preg_match('/[b,k]$/', $str1, $r2);
    $v=$r1[0];
    if($r2[0] == "b"){
        $r=1;
        $c=$str2."_b";
    } else {
        $r=1000;
        $c=$str2."_k";
    }
    return array((int)$v,(int)$r, $c);
}

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