import json
import requests
import pandas as pd

PORT_NUMBER = 1234
BASE_URL = "http://localhost:" + str(PORT_NUMBER) + "/v1/"
HEADERS = {'Content-Type': 'application/json'}

"""
Explanation: Visualizing time series metabolome profile
by Kozo Nishida (Riken, Japan)
Software Requirments
Please install the following software packages to run this workflow:

KEGGscape
enhancedGraphics

Background
This is a sample workflow to automate complex Cytoscape data integaration/visualization process.  Please read the following document for more background:  

https://github.com/idekerlab/KEGGscape/wiki/How-to-visualize-time-series-metabolome-profile
End of explanation
"""


requests.get("http://localhost:1234/keggscape/v1/ath00020")
res = requests.get("http://localhost:1234/v1/networks/currentNetwork")
result = json.loads(res.content)
pathway_suid = result["data"]["networkSUID"]
print("Pathway SUID = " + str(pathway_suid))

"""
Explanation: Load a KGML pathway data file with KEGGscape REST API
End of explanation
"""


profile_csv = "https://raw.githubusercontent.com/idekerlab/KEGGscape/develop/wiki/data/light-dark-20.csv"
profile_df = pd.read_csv(profile_csv)
profile_df.head()

"""
Explanation: Load table data file as Pandas DataFrame
End of explanation
"""


profile = json.loads(profile_df.to_json(orient="records"))
# print(json.dumps(profile, indent=4))

new_table_data = {
    "key": "KEGG_NODE_LABEL",
    "dataKey": "KEGG",
    "data": profile
}

update_table_url =  BASE_URL + "networks/" + str(pathway_suid) + "/tables/defaultnode"
requests.put(update_table_url, data=json.dumps(new_table_data), headers=HEADERS)

"""
Explanation: Convert the DataFrame to JSON and send it to Cytoscape
End of explanation
"""


chart_entry = 'barchart: attributelist="ld20t14,ld20t16,ld20t20,ld20t24,ld20t28,ld20t32,ld20t36,ld20t40,ld20t44,ld20t48,ld20t52,ld20t56,ld20t60,ld20t64,ld20t68,ld20t72" colorlist="up:red,zero:red,down:red" showlabels="false"'

target_row_url = BASE_URL + "networks/" + str(pathway_suid) + "/tables/defaultnode/columns/KEGG"
res2 = requests.get(target_row_url)
matched = json.loads(res2.content)["values"]

df2 = pd.DataFrame(columns=["id", "chart"]);
df2["id"] = matched
df2["chart"] = chart_entry

data = json.loads(df2.to_json(orient="records"))
    
chart_data = {
    "key": "KEGG",
    "dataKey": "id",
    "data": data
}

requests.put(update_table_url, data=json.dumps(chart_data), headers=HEADERS)

"""
Explanation: Set values to the chart column
End of explanation
"""


custom_graphics_mapping = {
    "mappingType" : "passthrough",
    "mappingColumn" : "chart",
    "mappingColumnType" : "String",
    "visualProperty" : "NODE_CUSTOMGRAPHICS_1"
}

style_url = BASE_URL + "styles/KEGG Style/mappings"
requests.post(style_url, data=json.dumps([custom_graphics_mapping]), headers=HEADERS)

"""
Explanation: Create Visual Style for Custom Mapping
End of explanation
"""


