{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "21548521-0c70-4db4-8c07-624d7ca32220",
   "metadata": {},
   "source": [
    "# Objectives\n",
    "<div class=\"alert alert-block alert-info\" >\n",
    "\n",
    "After completing the lab you will be able to:\n",
    "\n",
    "* Work with Dash Callbacks\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27681b2e-7745-4ef2-a117-48b08c2f2f32",
   "metadata": {},
   "source": [
    "## Theme\n",
    "\n",
    "Extract average monthly arrival delay time and see how it changes over the year. Year range is from 2010 to 2020.\n",
    "\n",
    "## Expected Output\n",
    "\n",
    "Below is the expected result from the lab. Our dashboard application consists of three components:\n",
    "\n",
    "*  Title of the application\n",
    "*  Component to enter input year\n",
    "*  Chart conveying the average monthly arrival delay"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "268d06ba-7149-4760-be89-eb2795150fd0",
   "metadata": {},
   "source": [
    "## To do:\n",
    "\n",
    "Import required libraries and read the dataset\n",
    "\n",
    "1. Create an application layout\n",
    "\n",
    "2. Add title to the dashboard application using HTML H1 component\n",
    "\n",
    "3. Add an input text box using core input component\n",
    "\n",
    "4. Add the line chart using core graph component\n",
    "\n",
    "5. Run the app"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d83b1340-c907-42d2-9f5c-ba3b3f177272",
   "metadata": {},
   "source": [
    "# Downloading and Prepping Data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "841259dc-df10-4cee-b339-3af815aaa96e",
   "metadata": {},
   "source": [
    "If you are using local jupyter lab, then  add these lines in your code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c34d16f9-fd56-4375-afec-bdf062152884",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\n!pip install dash\\n!pip install dash==1.19.0\\n!pip install jupyter_dash\\n!pip install --upgrade plotly\\n!pip install jupyter-dash\\n'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"\n",
    "!pip install dash\n",
    "!pip install dash==1.19.0\n",
    "!pip install jupyter_dash\n",
    "!pip install --upgrade plotly\n",
    "!pip install jupyter-dash\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc2db84c-4794-46a7-b525-f6c57925b01a",
   "metadata": {},
   "source": [
    "## TASK 1 - Read the data\n",
    "\n",
    "Let's start with\n",
    "\n",
    "* Importing necessary libraries\n",
    "* Reading the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "32805326-d248-49a3-acf5-50a8c55a9d7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import required libraries\n",
    "import pandas as pd\n",
    "import plotly.graph_objects as go\n",
    "#import dash\n",
    "from jupyter_dash import JupyterDash\n",
    "import dash_html_components as html\n",
    "import dash_core_components as dcc\n",
    "from dash.dependencies import Input, Output\n",
    "\n",
    "# Read the airline data into pandas dataframe\n",
    "airline_data =  pd.read_csv('airline_data.csv', \n",
    "                            encoding = \"ISO-8859-1\",\n",
    "                            dtype={'Div1Airport': str, 'Div1TailNum': str, \n",
    "                                   'Div2Airport': str, 'Div2TailNum': str})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b9b250b-4d25-454c-a2b1-5df441676c9b",
   "metadata": {},
   "source": [
    "## TASK 2 - Create dash application and get the layout skeleton\n",
    "\n",
    "Next, we create a skeleton for our dash application. Our dashboard application layout has three components as seen before:\n",
    "\n",
    "* Title of the application\n",
    "* Component to enter input year inside a layout division\n",
    "* Chart conveying the average monthly arrival delay inside a layout division"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65d8bba6-be8c-4e93-bf67-ebc37968da6a",
   "metadata": {},
   "source": [
    "Mapping to the respective Dash HTML tags:\n",
    "\n",
    "* Title added using __html.H1()__ tag\n",
    "* Layout division added using __html.Div()__ and input component added using __dcc.Input()__ tag inside the layout division.\n",
    "* Layout division added using __html.Div()__ and chart added using __dcc.Graph()__ tag inside the layout division."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "1a76d8e1-9f84-4543-917a-e0126f6bebc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a dash application\n",
    "#app = dash.Dash(__name__)\n",
    "app = JupyterDash(__name__) #This line used for JupyterLab\n",
    "\n",
    "# Get the layout of the application and adjust it.\n",
    "# Create an outer division using html.Div and add title to the dashboard using html.H1 component\n",
    "# Add a html.Div and core input text component\n",
    "# Finally, add graph component.\n",
    "app.layout = html.Div(children=[html.H1('Airline Performance Dashboard',\n",
    "style={'textAlign': 'center', 'color': '#503D36', 'font-size': 40}), html.Div([\"Input Year \", dcc.Input(id=\"input-year\", value=2010, type=\"number\",style={'height': 50,'font-size': 35}),], \n",
    "                                style={'font-size': 40}),\n",
    "                                html.Br(),\n",
    "                                html.Br(),\n",
    "                                html.Div(dcc.Graph(id=\"line-plot\")),\n",
    "                                ])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fe0a343-a43d-4ad1-995c-69ee459a8094",
   "metadata": {},
   "source": [
    "## TASK 3 - Update layout components\n",
    "### Application title\n",
    "\n",
    "* Heading reference: __Plotly H1 HTML Component__\n",
    "* Title as __Airline Performance Dashboard__\n",
    "* Use __style__ parameter and make the title __center__ aligned, with color code __#503D36__, and font-size as __40__. Check __More about HTML__ section here.\n",
    "\n",
    "### Input component\n",
    "* Update __dcc.Input__ component __id__ as __input-year__, default __value__ as __2010__, and __type__ as __number__. Use __style__ parameter and assign height of the input box to be __50px__ and __font-size__ to be __35__.\n",
    "* Use __style__ parameter and assign __font-size__ as __40__ for the whole division.\n",
    "\n",
    "### Output component\n",
    "* Add __dcc.Graph()__ component to the second division.\n",
    "* Update __dcc.Graph__ component __id__ as ___line-plot__."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b631add2-d97f-4a44-8e2f-44817cccfc72",
   "metadata": {},
   "source": [
    "## TASK 4 - Add the application callback function\n",
    "The core idea of this application is to get year as user input and update the dashboard in real-time. We will be using callback function for the same.\n",
    "\n",
    "Steps:\n",
    "\n",
    "* Define the callback decorator\n",
    "* Define the callback function that uses the input provided to perform the computation\n",
    "* Create graph and return it as an output\n",
    "* Run the application"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83f74970-46e1-4abe-9379-4cdc86d2837a",
   "metadata": {},
   "source": [
    "## TASK 5 - Update the callback function\n",
    "### Callback decorator\n",
    "\n",
    "* Refer examples provided here\n",
    "* Update output component id parameter with the id provided in the dcc.Graph() component and component property as figure.\n",
    "* Update input component id parameter with the id provided in the dcc.Input() component and component property as value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3c261742-3590-4b8b-b504-8860165b67d9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"100%\"\n",
       "            height=\"650\"\n",
       "            src=\"http://127.0.0.1:8050/\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x2428d6a6e80>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# add callback decorator\n",
    "@app.callback(Output(component_id='line-plot', component_property=\"figure\"),\n",
    "               Input(component_id='input-year', component_property='value'))\n",
    "\n",
    "# Add computation to callback function and return graph\n",
    "def get_graph(entered_year):\n",
    "    # Select data based on the entered year\n",
    "    df =  airline_data[airline_data['Year']==int(entered_year)]\n",
    "    \n",
    "    # Group the data by Month and compute average over arrival delay time.\n",
    "    line_data = df.groupby('Month')['ArrDelay'].mean().reset_index()\n",
    "    \n",
    "    # \n",
    "    fig = go.Figure(data=go.Scatter(x=line_data['Month'], y=line_data['ArrDelay'], mode='lines', marker=dict(color='green')))\n",
    "    fig.update_layout(title=\" Month vs Average Flight Delay Time\", xaxis_title=\"Month\", yaxis_title=\"ArrDelay\")\n",
    "    return fig\n",
    "\n",
    "# Run the app\n",
    "if __name__ == '__main__':\n",
    "    #app.run_server()\n",
    "    #For JupyterLab\n",
    "    #app.run_server(mode='jupyterlab', port = 8090, dev_tools_ui=True, debug=True,dev_tools_hot_reload =True, threaded=True)\n",
    "    \n",
    "    # Run app and display result inline in the notebook\n",
    "    app.run_server(mode='inline')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa86cd03-1fdc-4449-abec-c4d9d67365bf",
   "metadata": {},
   "source": [
    "## Congratulations, you have successfully created your dash application!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a1e7e520-3884-426e-a2fa-923c16e1cb0f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}