import pandas
import os

#
# takes in a 'change' csv file, and writes out a modified csv
#
def create_modified_changedata( changedata, newchangedata ):
    with open(changedata) as change, open(newchangedata, "w") as new:
        # first, write out the column names
        new.write("time,entropy\n")
        for line in change:
            data = line.split(',')
            new.write("{},{}\n".format(data[0],data[1]))

def get_links_to_inflection_files( changedata, coredata ):
    files = {} 

    print(changedata)
    print(coredata)

    timeids = []
    with open(changedata) as change:
            # skip the first line
            # current format does not have column names, so we don't do this
        # next(change)
        for line in change:
            data = line.split(',')
            if float(data[2]) > 0.0:
                timeids.append(int(float(data[0])))

    df = pandas.read_csv(coredata)
    for i in timeids:
        dfquery = df[(df["phi"] == -180) & (df["theta"] == -38) & (df["time"] == i)]
        files[i] = dfquery.iloc[0]["FILE"]

    return files

def create_entropy_feed( outfile, entropydata, imgfiles ):
    with open(outfile, "w") as outfile:
        outfile.write("""
<html>
<head>
    <meta charset=\"UTF-8\">
    <link href=\"cinema/c3/c3.min.css\" rel=\"stylesheet\">
    <link href=\"cinema/change/feed.css\" rel=\"stylesheet\">
    <link href=\"cinema/cinema_newsfeed/cinema/newsfeed/0.5/feed.css\" rel=\"stylesheet\">

    <script src=\"https://d3js.org/d3.v5.min.js\"></script>
    <script src=\"cinema/c3/c3.min.js\" charset=\"utf-8\"></script>
</head>

<body>
<div class=\"container\">
<header>
<h2>Cinema:Change Detection</h2>
</header>

<article>
<table cellpadding=\"5px\">
<tr>
<td><div id=\"chart\" class=\"chart\"></div></td>\n""")

        for f in imgfiles:
            outfile.write("<td><img class=\"snapshot\" src=\"cinema/global.cdb/{}\" ></img></td>\n".format(imgfiles[f]))

        outfile.write("""</tr>
</table>
</article>

<footer>&nbsp</footer>
</div>

<script>
var chart = c3.generate({
    size: {
        height: 150,
        width:  480
    },
    data: {
        x: 'time',\n""")
        outfile.write("        url: '{}',\n".format(entropydata))
        outfile.write("""
        types: {
            entropy: 'area'
        }
    },
    legend: {
        show: false
    },
    axis: {
        y: {
            label: {
                text: \"Entropy\",
                position: \"outer-middle\"
            },
            tick: {
                show: false
            }
        },
        x: {
            label: {
                text: \"Time ID\",
                position: \"outer-center\"
            }
        }
    }
});

</script>
</body>
</html>
""")

    return
