from flask import Flask, jsonify, request
import geopandas as gpd
import matplotlib.pyplot as plt
import matplotlib
from flask_cors import CORS
import matplotlib.font_manager as fm

import requests
from io import BytesIO
import base64


# to start the server please run: python -m flask run

matplotlib.use('Agg')
title_font = fm.FontProperties(family='Arial', style='normal', size=10, weight='normal', stretch='normal')

app = Flask(__name__)
CORS(app)

def generate_image(gdf):
    fig, ax = plt.subplots(figsize=(10, 10))

   # gdf['coords'] = gdf['geometry'].apply(lambda x: x.representative_point().coords[:])
   # gdf['coords'] = [coords[0] for coords in gdf['coords']]

    gdf.plot(ax=ax)

    #for idx, row in gdf.iterrows():
    #    plt.annotate(s=row['prop0'], xy=row['coords'], horizontalalignment='center')
    ax.set_title('Store floor plan', fontproperties=title_font)
    gdf.apply(lambda x:
        ax.annotate(text=x['prop0'], 
        xy=(x.geometry.centroid.x, x.geometry.centroid.y+0.1),
        ha='center')  
        if x['type']=='gate' else 
        ax.annotate(text=x['prop0'], 
        xy=(x.geometry.centroid.x, x.geometry.centroid.y),
        bbox=dict(boxstyle='round', color='k', fc='w', alpha=0.8),
        ha='center'), 
        axis=1)

    # Save the plot to a BytesIO object
    image_stream = BytesIO()
    plt.savefig(image_stream, format='png', dpi=300, bbox_inches='tight')
    image_stream.seek(0)

    # Encode the image to base64 for embedding in HTML
    encoded_image = base64.b64encode(image_stream.read()).decode('utf-8')
    return encoded_image

@app.route("/")
def hello_world():
    print('hee')
    startingPointId = request.args.get('startingPointId')
    print("From: "+startingPointId)

    # pre Step: getting the path lineString coordinates
    api_url = "http://localhost:3000/getShortestPath?productLocationId=A1&startingPointId="+startingPointId

    response = requests.get(api_url)
    coordinates = response.json()
    print(str(coordinates[-1]))
    

    # Step 1: Read the GeoJSON file using GeoPandas
    # https://en.wikipedia.org/wiki/GeoJSON
    geojson_str = '''
    {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [100.0, 0.0],
            [101.0, 0.0],
            [101.0, 1.0],
            [100.0, 1.0],
            [100.0, 0.0]
          ]
        ]
      },
      "properties": {
        "prop0": "A1",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [101.1, 0.0],
            [104.0, 0.0],
            [104.0, 1.0],
            [101.1, 1.0],
            [101.1, 0.0]
          ]
        ]
      },
      "properties": {
        "prop0": "A2",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [104.1, 0.0],
            [107.0, 0.0],
            [107.0, 1.0],
            [104.1, 1.0],
            [104.1, 0.0]
          ]
        ]
      },
      "properties": {
        "prop0": "A3",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },

    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [100.0, 1.7],
            [102.0, 1.7],
            [102.0, 3.0],
            [100.0, 3.0],
            [100.0, 1.7]
          ]
        ]
      },
      "properties": {
        "prop0": "B1",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [102.1, 1.7],
            [103.1, 1.7],
            [103.1, 3.0],
            [102.1, 3.0],
            [102.1, 1.7]
          ]
        ]
      },
      "properties": {
        "prop0": "B2",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [103.2, 2.4],
            [104.5, 2.4],
            [104.5, 3.0],
            [103.2, 3.0],
            [103.2, 2.4]
          ]
        ]
      },
      "properties": {
        "prop0": "B3",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [103.2, 1.7],
            [104.5, 1.7],
            [104.5, 2.3],
            [103.2, 2.3],
            [103.2, 1.7]
          ]
        ]
      },
      "properties": {
        "prop0": "B4",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [105.2, 1.7],
            [107.0, 1.7],
            [107.0, 3.0],
            [105.2, 3.0],
            [105.2, 1.7]
          ]
        ]
      },
      "properties": {
        "prop0": "B5",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },

    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [100.0, 3.6],
            [101.4, 3.6],
            [101.4, 4.9],
            [100.0, 4.9],
            [100.0, 3.6]
          ]
        ]
      },
      "properties": {
        "prop0": "C1",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [102.1, 3.6],
            [103.1, 3.6],
            [103.1, 4.9],
            [102.1, 4.9],
            [102.1, 3.6]
          ]
        ]
      },
      "properties": {
        "prop0": "C2",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [103.2, 3.6],
            [104.5, 3.6],
            [104.5, 4.9],
            [103.2, 4.9],
            [103.2, 3.6]
          ]
        ]
      },
      "properties": {
        "prop0": "C3",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [105.2, 3.6],
            [107.0, 3.6],
            [107.0, 4.9],
            [105.2, 4.9],
            [105.2, 3.6]
          ]
        ]
      },
      "properties": {
        "prop0": "C4",
        "prop1": { "this": "that" },
        "type": "section"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [100, 1.35]
      },
      "properties": {
        "prop0": "GATE 1",
        "prop1": { "this": "that" },
        "type": "gate"
      }
    },{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [107, 1.35]
      },
      "properties": {
        "prop0": "GATE 2",
        "prop1": { "this": "that" },
        "type": "gate"
      }
    },{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [107, 3.3]
      },
      "properties": {
        "prop0": "GATE 3",
        "prop1": { "this": "that" },
        "type": "gate"
      }
    },{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [104.85, 5]
      },
      "properties": {
        "prop0": "GATE 4",
        "prop1": { "this": "that" },
        "type": "gate"
      }
    },{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [101.75, 5]
      },
      "properties": {
        "prop0": "GATE 5",
        "prop1": { "this": "that" },
        "type": "gate"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [100, 3.3]
      },
      "properties": {
        "prop0": "GATE 6",
        "prop1": { "this": "that" },
        "type": "gate"
      }
    },'''+''' {
        "type": "Feature",
        "geometry": {
            "type": "LineString",
            "coordinates": 
            '''+str(coordinates)+'''
        }
        },
        {
        "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates":
                '''+str(coordinates[-1])+'''
        }
    }
    ]
    }'''

    gdf = gpd.read_file(geojson_str, driver='GeoJSON')

    # Step 2: Create a plot using Matplotlib
    img = generate_image(gdf)

    return jsonify({"image":img})