__copyright__ = "Reiner Lemoine Institut, Zentrum für nachhaltige Energiesysteme Flensburg"
__license__   = "GNU Affero General Public License Version 3 (AGPL-3.0)"
__url__       = "https://github.com/openego/data_processing/blob/master/LICENSE"
__author__    = "wolfbunke, Ludee"

"""
Explanation: <img src="http://193.175.187.164/static/OEP_logo_2_no_text.svg" alt="OpenEnergy Platform" height="100" width="100"  align="left"/>
OpenEnergy Platform
<br>
End of explanation
"""


import requests
import pandas as pd
from IPython.core.display import HTML

# oedb
oep_url= 'http://oep.iks.cs.ovgu.de/'

# token
your_token = ''

"""
Explanation: Tutorial - How to work with the OpenEnergy Platform (OEP)
<br>
<div class="alert alert-block alert-danger">
This is an important information!
</div>
<div class="alert alert-block alert-info">
This is an information!
</div>
<div class="alert alert-block alert-success">
This is your task!
</div>

This tutorial gives you an overview of the OpenEnergy Platform and how you can work with the REST-full-HTTP API in Python. <br>
The full API documentaion can be found on ReadtheDocs.io.
Part III
0 Setup token <br>
1 Select data <br>
2 Make a pandas dataframe <br>
3 Plot a dataframe (geo plot)
Part III
0. Setup token
<br>
<div class="alert alert-block alert-danger">
Do not push your token to GitHub!
</div>
End of explanation
"""


import geopandas as gpd
from shapely.geometry import Point
import shapely.wkt
from shapely import wkb
from geoalchemy2.shape import to_shape

# select powerplant data
schema = 'supply'
table = 'ego_dp_conv_powerplant'
where = 'version=v0.2.10'

conv_powerplants = requests.get(oep_url+'/api/v0/schema/'+schema+'/tables/'+table+'/rows/?where='+where, )
conv_powerplants.status_code

"""
Explanation: 1. Select data
End of explanation
"""


# select borders
schema = 'boundaries'
table = 'bkg_vg250_2_lan_mview'

vg = requests.get(oep_url+'/api/v0/schema/'+schema+'/tables/'+table+'/rows/')
vg.status_code

"""
Explanation: <div class="alert alert-block alert-info">
**200** succesfully selected data! <br>
</div>
End of explanation
"""


df_pp = pd.DataFrame(conv_powerplants.json())
df_vg = pd.DataFrame(vg.json())

"""
Explanation: <div class="alert alert-block alert-info">
**200** succesfully selected data! <br>
</div>

2. Make a pandas dataframe
End of explanation
"""


df_pp.info()

df_pp.columns

#df_pp
df_vg

"""
Explanation: Let's take a look into our data
End of explanation
"""


import geopandas as gpd
import shapely
import matplotlib.pyplot as plt
%matplotlib inline

# transform WKB to WKT / Geometry
df_pp['geom'] = df_pp['geom'].apply(lambda x:shapely.wkb.loads(x, hex=True))
df_vg['geom'] = df_vg['geom'].apply(lambda x:shapely.wkb.loads(x, hex=True))

# plot powerplants
crs = {'init' :'epsg:4326'}
gdf_pp = gpd.GeoDataFrame(df_pp, crs=crs, geometry=df_pp.geom)
base = gdf_pp.plot(color='white', edgecolor='black',figsize=(8, 8))
gdf_pp.plot(ax=base)
plt.show()


# plot borders
crs = {'init' :'epsg:3035'}
gdf_vg = gpd.GeoDataFrame(df_pp, crs=crs, geometry=df_vg.geom)
base = gdf_vg.plot(color='white', edgecolor='black',figsize=(8, 8))
gdf_vg.plot(ax=base)

plt.show()

# transform WKB to WKT / Geometry
crs1 = {'init' :'epsg:4326'}
crs2 = {'init' :'epsg:3035'}

gdf_pp = gpd.GeoDataFrame(df_pp, crs=crs1, geometry=df_pp.geom)
gdf_vg = gpd.GeoDataFrame(df_vg, crs=crs2, geometry=df_vg.geom)

base = gdf_vg.plot(color='white', edgecolor='black',figsize=(10, 10))

gdf_pp.plot(ax=base)
#gdf_vg.plot(ax=base)

plt.show()

"""
Explanation: 3. Plot a dataframe (geo plot)
End of explanation
"""


from shapely import geos
from geoalchemy2.shape import to_shape
from shapely.geometry import Point

from ipywidgets import widgets
from IPython.display import display
from IPython.core.display import HTML
from geoalchemy2 import Geometry, WKTElement
import requests
import pandas as pd
import mplleaflet

plants_data = requests.get(oep_url+'/api/v0/schema/model_draft/tables/ego_dp_supply_conv_powerplant/rows/?where=scenario=Status+Quo&limit=910',)
regions  =  requests.get(oep_url+'/api/v0/schema/model_draft/tables/renpass_gis_parameter_region/rows/?where=stat_level=999',)
regions.status_code
plants_data.status_code

sq_plants = pd.DataFrame(plants_data.json())
renpass_region_df = pd.DataFrame(regions.json())

# transform WKB to WKT / Geometry
crs = {'init' :'epsg:4326'}

sq_plants['geom'] =sq_plants['geom'].apply(lambda x:shapely.wkb.loads(x, hex=True))
renpass_region_df['geom'] =renpass_region_df['geom'].apply(lambda x:shapely.wkb.loads(x, hex=True))

gdf_plants = gpd.GeoDataFrame(sq_plants, crs=crs, geometry=sq_plants.geom)
gdf_regions = gpd.GeoDataFrame(renpass_region_df, crs=crs, geometry=renpass_region_df.geom)

base = gdf_regions.plot(color='white', edgecolor='black',figsize=(10, 10))

gdf_plants.plot(ax=base)


plt.show()

"""
Explanation: <div class="alert alert-block alert-danger">
bug under ubuntu
</div>
End of explanation
"""


import folium
from folium import plugins
import matplotlib.pyplot as plt
%matplotlib inline

# define map region
map = folium.Map(location=[51, 9], zoom_start=6)

# Use column lon / lat in order to plot map
for name, row in df_pp.iloc[:1000].iterrows():
    folium.Marker([row["lat"], row["lon"]], popup=row["type"] ).add_to(map)
#map.create_map('plants.html')
map

"""
Explanation: Point Plot
End of explanation
"""


stops_heatmap = folium.Map(location=[51, 9], zoom_start=6)
stops_heatmap.add_child(plugins.HeatMap([[row["lat"], row["lon"]] for capacity, row in df_pp.iloc[:1000].iterrows()]))
stops_heatmap.save("heatmap.html")
stops_heatmap

"""
Explanation: Heat plot for locations
End of explanation
"""


