{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " * Serving Flask app \"__main__\" (lazy loading)\n",
      " * Environment: production\n",
      "   WARNING: This is a development server. Do not use it in a production deployment.\n",
      "   Use a production WSGI server instead.\n",
      " * Debug mode: on\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      " * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n",
      " * Restarting with stat\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "1",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[0;31mSystemExit\u001b[0m\u001b[0;31m:\u001b[0m 1\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/philipharmon/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py:3334: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.\n",
      "  warn(\"To exit: use 'exit', 'quit', or Ctrl-D.\", stacklevel=1)\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import datetime as dt\n",
    "\n",
    "import sqlalchemy\n",
    "from sqlalchemy.ext.automap import automap_base\n",
    "from sqlalchemy.orm import Session\n",
    "from sqlalchemy import create_engine, func\n",
    "\n",
    "from flask import Flask, jsonify\n",
    "\n",
    "#################################################\n",
    "# Database Setup\n",
    "#################################################\n",
    "engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n",
    "Base = automap_base()\n",
    "Base.prepare(engine, reflect=True)\n",
    "\n",
    "# Base.metadata.tables # Check tables, not much useful\n",
    "# Base.classes.keys() # Get the table names\n",
    "\n",
    "Measurement = Base.classes.measurement\n",
    "Station = Base.classes.station\n",
    "\n",
    "#################################################\n",
    "# Flask Setup\n",
    "#################################################\n",
    "app = Flask(__name__)\n",
    "\n",
    "\n",
    "#################################################\n",
    "# Flask Routes\n",
    "#################################################\n",
    "\n",
    "@app.route(\"/\")\n",
    "def welcome():\n",
    "    \"\"\"List all available api routes.\"\"\"\n",
    "    return (\n",
    "        f\"Available Routes:<br/>\"\n",
    "        f\"Precipitation: /api/v1.0/precipitation<br/>\"\n",
    "        f\"List of Stations: /api/v1.0/stations<br/>\"\n",
    "        f\"Temperature for one year: /api/v1.0/tobs<br/>\"\n",
    "        f\"Temperature stat from the start date(yyyy-mm-dd): /api/v1.0/yyyy-mm-dd<br/>\"\n",
    "        f\"Temperature stat from start to end dates(yyyy-mm-dd): /api/v1.0/yyyy-mm-dd/yyyy-mm-dd\"\n",
    "    )\n",
    "\n",
    "@app.route('/api/v1.0/<start>')\n",
    "def get_t_start(start):\n",
    "    session = Session(engine)\n",
    "    queryresult = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n",
    "        filter(Measurement.date >= start).all()\n",
    "    session.close()\n",
    "\n",
    "    tobsall = []\n",
    "    for min,avg,max in queryresult:\n",
    "        tobs_dict = {}\n",
    "        tobs_dict[\"Min\"] = min\n",
    "        tobs_dict[\"Average\"] = avg\n",
    "        tobs_dict[\"Max\"] = max\n",
    "        tobsall.append(tobs_dict)\n",
    "\n",
    "    return jsonify(tobsall)\n",
    "\n",
    "@app.route('/api/v1.0/<start>/<stop>')\n",
    "def get_t_start_stop(start,stop):\n",
    "    session = Session(engine)\n",
    "    queryresult = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n",
    "        filter(Measurement.date >= start).filter(Measurement.date <= stop).all()\n",
    "    session.close()\n",
    "\n",
    "    tobsall = []\n",
    "    for min,avg,max in queryresult:\n",
    "        tobs_dict = {}\n",
    "        tobs_dict[\"Min\"] = min\n",
    "        tobs_dict[\"Average\"] = avg\n",
    "        tobs_dict[\"Max\"] = max\n",
    "        tobsall.append(tobs_dict)\n",
    "\n",
    "    return jsonify(tobsall)\n",
    "\n",
    "@app.route('/api/v1.0/tobs')\n",
    "def tobs():\n",
    "    session = Session(engine)\n",
    "    lateststr = session.query(Measurement.date).order_by(Measurement.date.desc()).first()[0]\n",
    "    latestdate = dt.datetime.strptime(lateststr, '%Y-%m-%d')\n",
    "    querydate = dt.date(latestdate.year -1, latestdate.month, latestdate.day)\n",
    "    sel = [Measurement.date,Measurement.tobs]\n",
    "    queryresult = session.query(*sel).filter(Measurement.date >= querydate).all()\n",
    "    session.close()\n",
    "\n",
    "    tobsall = []\n",
    "    for date, tobs in queryresult:\n",
    "        tobs_dict = {}\n",
    "        tobs_dict[\"Date\"] = date\n",
    "        tobs_dict[\"Tobs\"] = tobs\n",
    "        tobsall.append(tobs_dict)\n",
    "\n",
    "    return jsonify(tobsall)\n",
    "\n",
    "@app.route('/api/v1.0/stations')\n",
    "def stations():\n",
    "    session = Session(engine)\n",
    "    sel = [Station.station,Station.name,Station.latitude,Station.longitude,Station.elevation]\n",
    "    queryresult = session.query(*sel).all()\n",
    "    session.close()\n",
    "\n",
    "    stations = []\n",
    "    for station,name,lat,lon,el in queryresult:\n",
    "        station_dict = {}\n",
    "        station_dict[\"Station\"] = station\n",
    "        station_dict[\"Name\"] = name\n",
    "        station_dict[\"Lat\"] = lat\n",
    "        station_dict[\"Lon\"] = lon\n",
    "        station_dict[\"Elevation\"] = el\n",
    "        stations.append(station_dict)\n",
    "\n",
    "    return jsonify(stations)\n",
    "\n",
    "@app.route('/api/v1.0/precipitation')\n",
    "def precipitation():\n",
    "    session = Session(engine)\n",
    "    sel = [Measurement.date,Measurement.prcp]\n",
    "    queryresult = session.query(*sel).all()\n",
    "    session.close()\n",
    "\n",
    "    precipitation = []\n",
    "    for date, prcp in queryresult:\n",
    "        prcp_dict = {}\n",
    "        prcp_dict[\"Date\"] = date\n",
    "        prcp_dict[\"Precipitation\"] = prcp\n",
    "        precipitation.append(prcp_dict)\n",
    "\n",
    "    return jsonify(precipitation)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    app.run(debug=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
