#!/usr/bin/env python2
import os
os.environ[ 'HOME' ] = '/tmp/'

import cgi, cgitb
cgitb.enable()

import pandas as pd
import numpy as np
import cgi, cgitb, urllib, jinja2, json
from bokeh.plotting import figure,show
from bokeh.embed import components
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.palettes import Spectral5, viridis
httpfrom = cgi.FieldStorage()
SID = httpfrom.getvalue('sID')
if SID == None :
    SID='Stomata_density'
#SID="heat%SS"
#--- variation ------------------------------------------------------
phenohead={'phytate_ug/ml': 'Free phosphorus content(ug/ml)(Phytate)', 'Water_stress_T': 'Water stress', 'Stomata_density': 'Stomata density', 'heat%SS': '%seed set under heat stress at reproductive stage', 'Bph': 'Bph marker detection', 'salt(repro)%SS': '%seed set under salt stress at reproductive stage', 'Amylose': 'Amylose content', 'Stomata_Size': 'Stomata Size', 'Aroma': 'Aromatic rice', 'Irondensity_2000-1-2': 'Iron density (2000-1-2)', 'Submergence%PSS': '%plant survival under submergence at seedling stage', 'HighYield': 'High Yield', 'Iron_toxic_2000-1-2': 'Iron toxic (2000-1-2)', '%Recovery': '%Plant recovery after Water stress', 'Blast': 'Blast Resistant', 'male_sterile%SS': '%seed set under normal condition (male sterility)', 'cold%SS': '%seed set under clod stress at reproductive stage'}
pheno=pd.read_csv('phenotype.txt', sep='\t', header=0)


if len(pheno[pheno[SID] >= 0][SID].unique()) <=5 :
	pheno[SID]=pheno[SID].astype(str)
	ptd=pheno.groupby(SID)["Name"].nunique()
	x_la=ptd.index.tolist()
	x_la=map(str,x_la)[1:]
	topmem=ptd.tolist()[1:]
	variety=[pheno[pheno[SID] == x ]['Name'].tolist() for x in ptd.index.tolist() ][1:]
	fac_colo=viridis(len(x_la))
	tza=zip(x_la, variety)
	variatyurl='http://sinin.kps.ku.ac.th/mutant/variety.py?sID='
	tza=zip(x_la, variety)
	#--------------------------------------------------------------------
	source = ColumnDataSource(data=dict(
	    x=x_la,
	    y=topmem,
	    desc=variety,
	))
	hover = HoverTool(tooltips=[("desc", "@desc")])
	plot = figure(plot_width=800, plot_height=400, tools=[hover,'save'], title="Note: -9 means missing value.", x_range=x_la, responsive = True)
	plot.vbar(x='x', top='y', width=1, source=source,
	       line_color="white", fill_color=fac_colo, hover_color="red", )
	plot.xgrid.grid_line_color = None
	plot.y_range.start = 0
	plot.xaxis.major_label_orientation = 0.8
	#plot.y_range.end = 10
	plot.legend.orientation = "horizontal"
	plot.legend.location = "top_center"
else:
	hist, edges=np.histogram(pheno[pheno[SID] >= 0][SID], bins=20)
	fac_colo=viridis(len(edges[1:]))
	plot=figure(plot_width=800, plot_height=400)
	plot.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color=fac_colo, line_color="white")
	plot.xgrid.grid_line_color = None
	plot.y_range.start = 0
	plot.xaxis.major_label_orientation = 0.8
	plot.legend.orientation = "horizontal"
	plot.legend.location = "top_center"

script, divplot = components(plot)


pheno=pd.read_csv('phenotype.txt', sep='\t', header=0)
pheno[SID]=pheno[SID].astype(str)
ptd=pheno.groupby(SID)["Name"].nunique()
x_la=ptd.index.tolist()
x_la=map(str,x_la)
variety=[pheno[pheno[SID] == x ]['Name'].tolist() for x in ptd.index.tolist() ][1:]
variatyurl='http://sinin.kps.ku.ac.th/mutant/variety.py?sID='
tza=zip(x_la, variety)

set4="""<div class="container-fluid" style='background-color: #5b1942'>
        <div class="container">
        <img src="http://sinin.kps.ku.ac.th/images/logo-1.png">
        <h1 style='color : #feffed; font-weight: bold;'>Search for individual phenotype data : </h1>
        <font size="3" color="#feffed"> Please select Phenotype from the list box  </font>
        </br>
            <form action="plot_phenotype.py" method="get" target="_self" align="center" class="form-inline">
            <select name='sID' class="form-control">
            	<option value="heat%SS"> Select Phenotype </option>
				<option value="heat%SS">%seed set under heat stress at reproductive stage</option>
				<option value="cold%SS">%seed set under clod stress at reproductive stage</option>
				<option value="salt(repro)%SS">%seed set under salt stress at reproductive stage</option>
				<option value="male_sterile%SS">%seed set under normal condition (male sterility)</option>	
				<option value="Submergence%PSS">%plant survival under submergence at seedling stage</option>											
				<option value="Water_stress_T">Water stress</option>
				<option value="%Recovery">%Plant recovery after Water stress</option>
				<option value="Blast">Blast Resistant</option>
				<option value="Bph">Bph marker detection</option>												
				<option value="Stomata_density">Stomata density</option>
				<option value="Stomata_Size">Stomata Size</option>
				<option value="Irondensity_2000-1-2">Iron density (2000-1-2)</option>
				<option value="Iron_toxic_2000-1-2">Iron toxic (2000-1-2)</option>				
				<option value="Amylose">Amylose content</option>
				<option value="Aroma">Aromatic rice</option>
				<option value="phytate_ug/ml">Free phosphorus content(ug/ml)(Phytate)</option>				
				<option value="HighYield">High Yield</option>
            </select>
            <input type="submit" value="Submit" class="btn btn-default" />    
      </form>
      <br>
    </div></div>
"""
set5="""
<!-- menu -->
<div class="container-fluid navbar-nav-scroll" style='background-color: #93276b'>
    <div class="container">
        <nav class="navbar navbar-expand-lg navbar-light">
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto bd-navbar-nav flex-row" >
                <li class="nav-item active">
                    <a class="nav-link" href="http://sinin.kps.ku.ac.th/mutant/" style="color: #ffffff ; font-weight: bold">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: #ffffff">
                    Search Tools
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                      <a class="dropdown-item" href="http://sinin.kps.ku.ac.th/mutant/plot_phenotype.py" target="_blank">Phenotype search</a>
                      <a class="dropdown-item" href="http://sinin.kps.ku.ac.th/mutant/variety.py" target="_blank">Variety search</a>
                      <a class="dropdown-item" href="http://sinin.kps.ku.ac.th/mutant/haplotype.py" target="_blank">Haplotype search</a>
                      <a class="dropdown-item" href="http://sinin.kps.ku.ac.th/mutant/genetable.py" target="_blank">Mutiple gene search</a>
                      <!-- <div class="dropdown-divider"></div>
                      <a class="dropdown-item" href="#">Something else here</a> -->
                    </div>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: #ffffff">
                    Genome Browser
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                      <a class="dropdown-item" href="http://sinin.kps.ku.ac.th/mbrowser/" target="_blank">Mbrowser</a>
                      <a class="dropdown-item" href="http://sinin.kps.ku.ac.th/varmu/tasuke_www/" target="_blank">TASUKE </a>
                    </div>
                </li>
            </ul>
            <div class="dropdown">
                  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Search Tools
                      <span class="caret"></span></button>
                      <ul class="dropdown-menu">
                        <li><a href="http://sinin.kps.ku.ac.th/mutant/plot_phenotype.py" target="_blank">Phenotype search</a></li>
                        <li class="divider">  </li>
                        <li><a href="http://sinin.kps.ku.ac.th/mutant/variety.py" target="_blank">Variety search</a></li>
                        <li class="divider"></li>
                        <li><a href="http://sinin.kps.ku.ac.th/mutant/haplotype.py" target="_blank">Haplotype search</a></li>
                      </ul>
            </div> 
        </div>
        </nav>
    </div>
</div>
<!-- end menu -->
"""
print """
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>individual phenotype data</title>
        <link rel="stylesheet" href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.6.min.css" type="text/css" />
        <script type="text/javascript" src="hhttps://cdn.bokeh.org/bokeh/release/bokeh-0.12.6.min.js"></script>
        <link rel="stylesheet" type="text/css" href="DataTables/datatables.min.css"/>
        <script type="text/javascript" src="DataTables/datatables.min.js"></script>
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
		<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
"""
print(script)
print "</head> \n <body> "
print set4
print set5
print '<div class="container">'
print "<h1 style='color : #28747a' >" +phenohead[SID]+ "</h1>"
print "<div  style='height: 70%;' >"
print(divplot)
print "</div>"
print "</br></br>"
#----------------------------
print "<div>"
print """	<script type='text/javascript'>
			  $(document).ready(function() {
			    $('#data_table').DataTable({dom: 'lBfrtip', buttons: [],
			            initComplete: function () {
			            this.api().columns().every( function () {
			                var column = this;
			                var select = $('<select><option value=""></option></select>')
			                    .appendTo( $(column.footer()).empty() )
			                    .on( 'change', function () {
			                        var val = $.fn.dataTable.util.escapeRegex(
			                            $(this).val()
			                        );
			 
			                        column
			                            .search( val ? '^'+val+'$' : '', true, false )
			                            .draw();
			                    } );
			 
			                column.data().unique().sort().each( function ( d, j ) {
			                    select.append( '<option value="'+d+'">'+d+'</option>' )
			                } );
			            } );
			        }
			    });
			} );
    		</script>
      """
print "<h2 style='color : #28747a'> Table of "+phenohead[SID]+ " value. </h2>"
print """
<table id="data_table" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Value</th>
                <th>Variaty</th>
            </tr>
        </thead>
        <tbody>
"""
for x in tza:
	if x[0] != '-9.0':
		for y in x[1]:
			print "<tr><td>"+x[0]+'</td><td><a href="'+variatyurl+y+'" target="_blank">'+y+"</a></td></tr> "

print """
        </tbody>
        <tfoot>
            <tr>
                <th>Value</th>
                <th>Variaty</th>
            </tr>
      </tfoot>
</table>
"""
print "</div>"
print "</div>"
print "</body> \n </html>"

















