import datetime as dt
import numpy as np
import pandas as pd
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify

#imported dependencies, set up database engine.

# access and query our SQLite database file

engine = create_engine("sqlite:///hawaii.sqlite")

# reflect the database into our classes.

Base = automap_base()

# code to reflect the database:

Base.prepare(engine, reflect=True)

#With the database reflected, we can save our references to each table. 

Measurement = Base.classes.measurement
Station = Base.classes.station

# create a session link from Python to our database 

session = Session(engine)

#define our Flask app

#This will create a Flask application called "app."

app = Flask(__name__)

#create welcome route 

#define the welcome route using the code below:

@app.route("/")

#Now our root, or welcome route, is set up. The next step is to add the routing information for 
#each of the other routes.

def welcome():
    return(
    '''
    Welcome to the Climate Analysis API!
    Available Routes:
    /api/v1.0/precipitation
    /api/v1.0/stations
    /api/v1.0/tobs
    /api/v1.0/temp/start/end
    ''')

#next route for the precipitation analysis

@app.route("/api/v1.0/precipitation")

#precipitation function 

#def precipitation():
   #prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)
   #precipitation = session.query(Measurement.date, Measurement.prcp).\
      #filter(Measurement.date >= prev_year).all()
   #return

#create a dic with date as the key and precipitation as the value. To do this, jsonify dict

def precipitation():
   prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)
   precipitation = session.query(Measurement.date, Measurement.prcp).\
    filter(Measurement.date >= prev_year).all()
   precip = {date: prcp for date, prcp in precipitation}
   return jsonify(precip)

#creating stations route 

#defining the route and route name 

@app.route("/api/v1.0/stations")

#with route defined, creating function called stations() and jsonyfing the LIST 

def stations():
    results = session.query(Station.station).all()
    stations = list(np.ravel(results))
    return jsonify(stations=stations)

#adding the monthly temparature route 

@app.route("/api/v1.0/tobs")

#creating temp_monthly() function 

def temp_monthly():
    prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)
    results = session.query(Measurement.tobs).\
      filter(Measurement.station == 'USC00519281').\
      filter(Measurement.date >= prev_year).all()
    temps = list(np.ravel(results))
    return jsonify(temps=temps)

#9.5.6 statistics route 

@app.route("/api/v1.0/temp/<start>")
@app.route("/api/v1.0/temp/<start>/<end>")

#creating function 

def stats(start=None, end=None):
    sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]

    if not end:
        results = session.query(*sel).\
            filter(Measurement.date >= start).\
            filter(Measurement.date <= end).all()
        temps = list(np.ravel(results))
        return jsonify(temps)

    results = session.query(*sel).\
        filter(Measurement.date >= start).\
        filter(Measurement.date <= end).all()
    temps = list(np.ravel(results))
    return jsonify(temps=temps)

    



