#!/usr/bin/env python3
#  -*- coding: utf-8 -*-

"""
Read files and defines functions to plot maps of Qatar

Author: Thomas Dobbelaere, Earth and Life Institute, UCLouvain, Belgium
Last modified: 19 July 2022
"""
from osgeo import osr,ogr
import numpy as np
import shapely.geometry
from matplotlib.patches import Polygon
from matplotlib.collections import LineCollection, PatchCollection
from typing import List, Union

def read_shp(shpfile: str) -> Union[List[np.ndarray], List[Polygon]]:
    driver = ogr.GetDriverByName('ESRI Shapefile')
    ds = driver.Open(shpfile,0)
    lyr = ds.GetLayer(0)
    val = []
    for f in lyr:
        geom = f.geometry()
        geometry_name = geom.GetGeometryName()
        if geometry_name in ['MULTIPOLYGON', 'MULTILINESTRING']:
            geos = geom  
        elif geometry_name in ['POLYGON', 'LINESTRING']:
            geos = [geom]
        else:
            raise ValueError(f"Unknown geometry type '{geometry_name}'")
        for geo in geos:
            if geo.GetGeometryName() == 'POLYGON':
                ring = geo.GetGeometryRef(0)
                pnts = np.array(ring.GetPoints())
                val.append(Polygon(pnts))
            elif geo.GetGeometryName() == 'LINESTRING':
                val.append(np.array(geo.GetPoints()))
    ds = None
    return val

utm_proj = osr.SpatialReference()
utm_proj.ImportFromProj4('+proj=utm +ellps=WGS84 +zone=39 +north')
lonlat_proj = osr.SpatialReference()
lonlat_proj.ImportFromProj4("+ellps=WGS84 +proj=lonlat")
to_utm = osr.CoordinateTransformation(lonlat_proj, utm_proj)
to_lonlat = osr.CoordinateTransformation(utm_proj, lonlat_proj)

# shape files
basedir = "/export/miro/students/tanselain/OpenOil"
path_to_shp = basedir+"/Indicators/Background_map"
land = read_shp(path_to_shp +"/PG_layer_poly_new/PG_layer_poly_new.shp")
borders = read_shp(path_to_shp+"/natural_earth/ne_10m_admin_0_boundary_lines_land.shp")
eez = read_shp(path_to_shp+"/qatar_eez/qatar_eez_line.shp")

def plot_landmark(ax, sources):
    # Put land, border and eez in background
    ax.add_collection(
        PatchCollection(land, linewidths=0.5, edgecolors='k', facecolors='lightgray')
    )
    ax.add_collection(LineCollection(borders, linewidth=0.5, linestyle='-', color='k'))
    ax.add_collection(LineCollection(eez, linewidth=2, color='darkgreen'))

    if "abu_fontas" in sources:
        ax.scatter(51.6269, 25.2061, s=50, c='#1f77b4')
        ax.text( 51.385, 25.2, "Abu Fontas", color='k', fontsize=12, \
                    fontweight='bold', ha='center', va='center')
    if "umm_al_houl" in sources:
        ax.scatter(51.633, 25.1135, s=50, c='#1f77b4')
        ax.text( 51.355, 25.1135, "Umm al Houl", color='k', fontsize=12, \
                    fontweight='bold', ha='center', va='center')
    if "ras_laffan" in sources:
        ax.scatter(51.5422, 25.9324, s=50, c='#1f77b4')
        ax.text(51.355, 25.89, "Ras Laffan", color='k', fontsize=12, \
                 fontweight='bold', ha='center', va='center')
    if "lusail" in sources:
        ax.scatter( 51.545, 25.31, s=50, c='#1f77b4' ,zorder=5)
        ax.text( 51.5, 25.29, 'Doha', color='k', fontsize=12, 
                    fontweight='bold', ha='right', va='center')
    

    ## SCALE ##
    """pstart = (50.15, 27.35, 0)
    length = 30*1000
    lw = 2
    h = 0.01
    Xstart, Ystart, _ = to_utm.TransformPoint(*pstart)
    pend =  to_lonlat.TransformPoint(Xstart+length, Ystart,0)
    ax.text(0.5*(pstart[0]+pend[0]), pend[1]+2*h, "30 km",\
                 va="bottom", ha="center", fontsize=12)
    ax.plot([pstart[0], pend[0]], [pstart[1],pend[1]], color="k", linewidth=lw)
    ax.plot([pstart[0], pstart[0]], [pstart[1]-h, pstart[1]+h], color="k", linewidth=lw)
    ax.plot([pend[0], pend[0]], [pend[1]-h, pend[1]+h], color="k", linewidth=lw)
    """
    # TICKS
    ax.set_xlim(50, 53.2)
    ax.set_ylim(24, 27.2)
    yticks = np.arange(24, 28, .5)
    ax.set_yticks(yticks)
    ax.set_yticklabels([f"{y}°N" for y in yticks])
    ax.tick_params(labelleft=True, labelbottom = True) 
    xticks = np.arange(50,53.5,0.5)
    ax.set_xticks(xticks)
    ax.set_xticklabels([f"{x}°E" for x in xticks])
    
    ax.set_aspect("equal")