import numpy as np
import os
############
#This program creates highchart graphs for a tagSNP linkage disequalibrium analysis
#This chart calls highcharts javascript package for graphing
#It requires output files with a suffix '.info' for processing
############

#Create range for x axis
rangenp = np.arange(0,1,0.01)

#Convert range to list as per highcharts requirements
sortedKeys=[]
for rangeItem in rangenp:
    sortedKeys.append(round(rangeItem,3))
#List for data values to be graphed
dataValues=[]

#Parse all output files with suffix '.info'
dirPath = "."
filenames = [f for f in os.listdir(dirPath) if "info" in f ]

#Write to file
outfile = open('tagSNPResults.html','w')
#File parse begin
for infile in filenames:
    freqCounts = {freq: [] for freq in rangenp}
    freqCounts = {}
    shortName = infile.split("info")[0]
    with open(infile) as fileread:
        for line in fileread:
            if not "concord" in line:
                linesplit = line.rstrip().split()
                if float(linesplit[-1]) != -1:
                    #print linesplit[-1]
                    #continue
                    #r-squared value
                    r2 = float(linesplit[-1])
                    #ignore '-1' r-squared
                    #Mean allele freq
                    freq = round(float(linesplit[5]), 2)
                    try:
                        freqCounts[freq].append(r2)
                    except KeyError:
                        freqCounts[freq] = [r2]

    #Obtain the average r-squared value for the range and input it into dataValues list, a format for highcharts graphing
    sortedvalueList=[]
    for k in sorted(freqCounts):
        freqCounts[k]=str(sum(freqCounts[k])/len(freqCounts[k]))
        sortedvalueList.append(freqCounts[k])
    dataValues.append("{name: '"+shortName+"',data:" +str(sortedvalueList).replace("'","")+"},")


def LineChart(Order,sortedKeys,dataValues,title):
    outfile.write( "        $('#chart-"+Order+"').highcharts({"+"\n")
    outfile.write( "            title: {"+"\n")
    outfile.write( "                text: '"+title+"'"+"\n")
    outfile.write( '            },'+"\n")
    outfile.write( "        plotOptions: {"+"\n")
    outfile.write( "            series: {"+"\n")
    outfile.write( "                marker: {"+"\n")
    outfile.write( "                    enabled: false"+"\n")
    outfile.write( "                }"+"\n")
    outfile.write( "            }"+"\n")
    outfile.write( "        },"+"\n")
    outfile.write( '            xAxis: {'+"\n")
    outfile.write( '            categories: ' + str(sortedKeys)+","+"\n")
    outfile.write( "            title: {"+"\n")
    outfile.write( "            enabled: true,"+"\n")
    outfile.write( "            text: 'Mean Allelic Frequency Range'"+"\n")
    outfile.write( "            }"+"\n")
    outfile.write( '            },'+"\n")
    outfile.write( "            title: {"+"\n")
    outfile.write( "            enabled: true,"+"\n")
    outfile.write( "            text: ''"+"\n")
    outfile.write( "            },"+"\n")
    outfile.write( '            yAxis: {'+"\n")
    outfile.write( '                min: -1.0,'+"\n")
    outfile.write( '                title: {'+"\n")
    outfile.write( "                    text: 'Mean r^2'"+"\n")
    outfile.write( '                }'+"\n")
    outfile.write( '            },'+"\n")
    outfile.write( '            legend: {'+"\n")
    outfile.write( '                enabled: false'+"\n")
    outfile.write( '            },'+"\n")
    outfile.write( "              legend: {"+"\n")
    outfile.write( "                itemStyle: {"+"\n")
    outfile.write( "                 font: '10pt Trebuchet MS, Verdana, sans-serif',"+"\n")
    outfile.write( "                 "+"\n")
    outfile.write( "              },"+"\n")
    outfile.write( "            enabled: true,"+"\n")
    outfile.write( "            align: 'right',"+"\n")
    outfile.write( "            backgroundColor: 'white',"+"\n")
    outfile.write( "            borderColor: 'black',"+"\n")
    outfile.write( "            borderWidth: 2,"+"\n")
    outfile.write( "            layout: 'vertical',"+"\n")
    outfile.write( "            verticalAlign: 'top',"+"\n")
    outfile.write( "            y: 40,"+"\n")
    outfile.write( "            shadow: true"+"\n")
    outfile.write( "        },"+"\n")
    outfile.write( '            credits: {'+"\n")
    outfile.write( '                enabled: false,'+"\n")
    outfile.write( '            },'+"\n")
    outfile.write( '            tooltip: {'+"\n")
    outfile.write( '                shared: true'+"\n")
    outfile.write( '            },'+"\n")
    outfile.write( '            series: ['+"\n")
    for dv in dataValues:
        outfile.write( dv+"\n")
    outfile.write( "                ]"+"\n")
    outfile.write( '            });'+"\n")
    return

outfile.write( '<html>'+"\n")
outfile.write( '<head>'+"\n")
outfile.write( '    '+"\n")
outfile.write( '    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>'+"\n")
outfile.write( '    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>'+"\n")
outfile.write( '    <style type="text/css">'+"\n")
outfile.write( '        '+"\n")
outfile.write( '        h1{'+"\n")
outfile.write( '            text-align: center;'+"\n")
outfile.write( '            font-family: "Goudy Old Style", Garamond, "Big Caslon", "Times New Roman", serif;'+"\n")
outfile.write( '            font-style: normal;'+"\n")
outfile.write( '            font-variant: normal;'+"\n")
outfile.write( '            '+"\n")
outfile.write( '            font-weight: bold;'+"\n")
outfile.write( '            position: absolute;'+"\n")
outfile.write( '            margin-left: auto;'+"\n")
outfile.write( '            margin-right: auto;'+"\n")
outfile.write( '            left: 0%;'+"\n")
outfile.write( '            right: 0;'+"\n")
outfile.write( '            top: 15%;'+"\n")
outfile.write( '            '+"\n")
outfile.write( '        }'+"\n")
outfile.write( '        .titlebox{'+"\n")
outfile.write( '            position: fixed;'+"\n")
outfile.write( '            top: -20;'+"\n")
outfile.write( '            width: 100%;'+"\n")
outfile.write( '            padding:0 0 0 0px;'+"\n")
outfile.write( '            background: #ccc;'+"\n")
outfile.write( '            height: 100px;'+"\n")
outfile.write( '            z-index: 1;'+"\n")
outfile.write( '            '+"\n")
outfile.write( '        }'+"\n")
outfile.write( '        '+"\n")
outfile.write( '        .chart {'+"\n")
outfile.write( '                height: 80%;'+"\n")
outfile.write( '                width: 80%;'+"\n")
outfile.write( '                margin:auto;'+"\n")
outfile.write( '                padding:7% 0 0 0px;'+"\n")
outfile.write( '        }'+"\n")
outfile.write( ''+"\n")
outfile.write( '        '+"\n")
outfile.write( '        .spacer {'+"\n")
outfile.write( '            height: 10px;'+"\n")
outfile.write( '        }'+"\n")
outfile.write( '        a {'+"\n")
outfile.write( '            background: #ddd;'+"\n")
outfile.write( '            color: #444;'+"\n")
outfile.write( '            font-family: "Book Antiqua", Palatino, "Palatino Linotype", "Palatino LT STD", Georgia, serif;'+"\n")
outfile.write( '            font-style: normal;'+"\n")
outfile.write( '            font-variant: normal;'+"\n")
outfile.write( '            text-align: center;'+"\n")
outfile.write( '            text-decoration: none;'+"\n")
outfile.write( '            padding: 0 0 0 0px;'+"\n")
outfile.write( '            display: block;'+"\n")
outfile.write( '          }'+"\n")
outfile.write( '        '+"\n")
outfile.write( '        '+"\n")
outfile.write( '        ul.vert-one{'+"\n")
outfile.write( '            margin:0;'+"\n")
outfile.write( '            margin-top: 10%;'+"\n")
outfile.write( '            padding:7% 0 0 0px;'+"\n")
outfile.write( '            list-style-type:none;'+"\n")
outfile.write( '            display:block;'+"\n")
outfile.write( '            font:bold 16px Helvetica Verdana, Arial, sans-serif;'+"\n")
outfile.write( '            line-height:300%;'+"\n")
outfile.write( '            width:18%;'+"\n")
outfile.write( '            position: fixed;'+"\n")
outfile.write( '        }'+"\n")
outfile.write( ''+"\n")
outfile.write( '        ul.vert-one li{'+"\n")
outfile.write( '            margin:0;'+"\n")
outfile.write( '            margin-top: 5 px;'+"\n")
outfile.write( '            margin-bottom: 10px;'+"\n")
outfile.write( '            padding:0;'+"\n")
outfile.write( '            border:1px solid black;'+"\n")
outfile.write( '            width: 100%;'+"\n")
outfile.write( '            padding:0 0 0 0px;'+"\n")
outfile.write( '            }'+"\n")
outfile.write( '        '+"\n")
outfile.write( '        ul.vert-one li a{'+"\n")
outfile.write( '            display:block;'+"\n")
outfile.write( '            text-decoration:none;'+"\n")
outfile.write( '            color:#fff;'+"\n")
outfile.write( '            background:grey;'+"\n")
outfile.write( '            padding:0 0 0 0px;'+"\n")
outfile.write( '            width:100%;}'+"\n")
outfile.write( '        '+"\n")
outfile.write( '        ul.vert-one li a:hover{'+"\n")
outfile.write( '            background: black;}'+"\n")
outfile.write( '        '+"\n")
outfile.write( '        ul.vert-one li a.current,ul.vert-one li a.current:hover{'+"\n")
outfile.write( '            background:grey;'+"\n")
outfile.write( '        }'+"\n")
outfile.write( '        .inline {'+"\n")
outfile.write( '            display:inline-block;'+"\n")
outfile.write( '            float: left;'+"\n")
outfile.write( '            '+"\n")
outfile.write( '            '+"\n")
outfile.write( '            '+"\n")
outfile.write( '        }'+"\n")
outfile.write( '    ${demo.css}'+"\n")
outfile.write( '    </style>'+"\n")
outfile.write( '    <script type="text/javascript">'+"\n")
outfile.write( '    $( document ).ready(function() {'+"\n")
outfile.write( "        $('a[href^="+'"#"'+"]').on('click', function(event) {"+"\n")
outfile.write( '    '+"\n")
outfile.write( "            var target = $(this.getAttribute('href'));"+"\n")
outfile.write( '        '+"\n")
outfile.write( '            if( target.length ) {'+"\n")
outfile.write( '                event.preventDefault();'+"\n")
outfile.write( "                $('html, body').stop().animate({"+"\n")
outfile.write( '                    scrollTop: target.offset().top'+"\n")
outfile.write( '                }, 1000);'+"\n")
outfile.write( '            }'+"\n")
outfile.write( '        })'+"\n")
outfile.write( '    });'+"\n")
outfile.write( '    $(function(changeChart) {'+"\n")
outfile.write( '        Highcharts.setOptions({'+"\n")
outfile.write( '            lang: {'+"\n")
outfile.write( "                thousandsSep: ','"+"\n")
outfile.write( '            },'+"\n")
outfile.write( "            colors: ['#50B432', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263','#6AF9C4','#ff66a3','#0073e6','#0059b3','#80dfff','#00e6e6','#ffbf80','#ff9933','#ffd11a','#ffe680']"+"\n")
outfile.write( '        });'+"\n")
outfile.write( '    $(function() {'+"\n")
LineChart('A',sortedKeys,dataValues, 'Depth of Coverage')
outfile.write( '        });'+"\n")
outfile.write( '    });'+"\n")
outfile.write( '    </script>'+"\n")
outfile.write( '</head>'+"\n")
outfile.write( '<body>'+"\n")
outfile.write( '<script src="https://code.highcharts.com/highcharts.js"></script>'+"\n")
outfile.write( '<script src="https://code.highcharts.com/modules/exporting.js"></script>'+"\n")
outfile.write( '<div class="titlebox">'+"\n")
outfile.write( '    <h1>ragTAG Analysis</h1>'+"\n")
outfile.write( '</div>'+"\n")
outfile.write( '<div id="chart-A" class="chart"></div> <!-- Container for Chart A -->'+"\n")
outfile.write( '<div class="spacer"></div>'+"\n")
outfile.write( '</body>'+"\n")
outfile.write( '</html>'+"\n")
