# Import required libraries
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.express as px

# Read the airline data into pandas dataframe
spacex_df = pd.read_csv("spacex_launch_dash.csv")
max_payload = spacex_df['Payload Mass (kg)'].max()
min_payload = spacex_df['Payload Mass (kg)'].min()

def site_filter(dataframe, site_name):
    return dataframe[dataframe['Launch Site'] == site_name]

# Create a dash application
app = dash.Dash(__name__)

# Create an app layout
app.layout = html.Div(children=[html.H1('SpaceX Launch Records Dashboard',
                                        style={'textAlign': 'center', 'color': '#503D36',
                                               'font-size': 40}),
                                # TASK 1: Add a dropdown list to enable Launch Site selection
                                # The default select value is for ALL sites
                                dcc.Dropdown(
                                    id='site-dropdown',
                                    options=[
                                        {'label': 'All Sites', 'value': 'allsite'},
                                        {'label': 'CCAFS LC-40', 'value': 'site1'},
                                        {'label': 'VAFB SLC-4E', 'value': 'site2'},
                                        {'label': 'KSC LC-39A', 'value': 'site3'},
                                        {'label': 'CCAFS SLC-40', 'value': 'site4'}
                                    ],
                                    value= 'allsite',
                                    placeholder= 'Select a Launch Site here',
                                    searchable= True
                                ),
                                html.Br(),

                                # TASK 2: Add a pie chart to show the total successful launches count for all sites
                                # If a specific launch site was selected, show the Success vs. Failed counts for the site
                                html.Div(dcc.Graph(id='success-pie-chart')),
                                html.Br(),

                                html.P("Payload range (Kg):"),
                                # TASK 3: Add a slider to select payload range
                                dcc.RangeSlider(id='payload-slider', min=0, max=10000, step=1000,
                                                marks={
                                                    0: '0',
                                                    1000: '1000 Kg',
                                                    2000: '2000 Kg',
                                                    3000: '3000 Kg',
                                                    4000: '4000 Kg',
                                                    5000: '5000 Kg',
                                                    6000: '6000 Kg',
                                                    7000: '7000 Kg',
                                                    8000: '8000 Kg',
                                                    9000: '9000 Kg',
                                                    10000: '10000'
                                                }, value=[min_payload, max_payload],
                                                allowCross=False
                                                ),

                                # TASK 4: Add a scatter chart to show the correlation between payload and launch success
                                html.Div(dcc.Graph(id='success-payload-scatter-chart')),
                                ])

# TASK 2:
# Add a callback function for `site-dropdown` as input, `success-pie-chart` as output
@app.callback(
    Output(component_id='success-pie-chart', component_property='figure'),
    Input(component_id='site-dropdown', component_property='value')
)
def get_pie_chart(entered_site):
    filtered_df = spacex_df
    if entered_site == 'allsite':
        all_data = filtered_df[filtered_df['class']==1]
        fig = px.pie(all_data, values='class',
                     names='Launch Site',
                     title='All Sites')
        return fig
    else:
        sites = {'site1': 'CCAFS LC-40', 'site2': 'VAFB SLC-4E', 'site3': 'KSC LC-39A', 'site4': 'CCAFS SLC-40'}
        site_data = site_filter(filtered_df, sites[entered_site]).groupby('class')['Launch Site'].count().to_frame('Launch')
        fig = px.pie(site_data, values='Launch',
                     names=site_data.index.values,
                     title=f'{sites[entered_site]} - Success V/s Failed Launch',
                     hover_name=['Success', 'Failed'])
        return fig

# TASK 4:
# Add a callback function for `site-dropdown` and `payload-slider` as inputs, `success-payload-scatter-chart` as output
@app.callback(
    Output(component_id='success-payload-scatter-chart', component_property='figure'),
    [
        Input(component_id='site-dropdown', component_property='value'),
        Input(component_id="payload-slider", component_property="value")
    ]
)
def get_scatter_plot(entered_site, payload_size):
    if entered_site == 'allsite':
        data = spacex_df[['Payload Mass (kg)', 'class', 'Booster Version Category']]
        data = data[(data['Payload Mass (kg)'] > payload_size[0]) & (data['Payload Mass (kg)'] < payload_size[1])]
        scatter_fig = px.scatter(data,
                                 x='Payload Mass (kg)', y='class',
                                 color='Booster Version Category',
                                 title='Correlation between Payload and Success for all sites')
        return scatter_fig
    else:
        sites = {'site1': 'CCAFS LC-40', 'site2': 'VAFB SLC-4E', 'site3': 'KSC LC-39A', 'site4': 'CCAFS SLC-40'}
        site_data = site_filter(spacex_df, sites[entered_site])[['Payload Mass (kg)', 'class', 'Booster Version Category']]
        site_data = site_data[(site_data['Payload Mass (kg)'] > payload_size[0]) & (site_data['Payload Mass (kg)'] < payload_size[1])]
        scatter_fig = px.scatter(site_data,
                                 x='Payload Mass (kg)', y='class',
                                 color='Booster Version Category',
                                 title=f'Correlation between Payload and Success for {sites[entered_site]}')
        return scatter_fig

# Run the app
if __name__ == '__main__':
    app.run_server()
