import time
import pandas as pd
import numpy as np

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

def get_filters():
    """
    Asks user to specify a city, month, and day to be analyzed

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('Hello! Let\'s explore some US bikeshare data!')
    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    while True:    
        city = input('Enter city of choice(chicago, new york city, washington): ').lower()
        if city not in ('chicago', 'new york city', 'washington'):
            print("Please enter correct city")
            continue
        else:
            break

    # TO DO: get user input for month (all, january, february, ... , june)
    months = ('all', 'january', 'february','march','april','may','june')
    while True:
        month = input('Enter month of choice, you can choose all: ').lower()
        if month not in months:
            print("Please enter correct choice of months: ")
            continue
        else:
            break

    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    days= ('all', 'monday', 'tuesday','wednesday','thursday','friday','saturday','sunday')    
    while True:
        day = input('Enter day of choice, you can choose all: ').lower()
        if day not in days:
            print("Please enter correct choice of days of the week ")
            
        else:
            break
            
     

    print('-'*40)
    return city, month, day


def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
    df = pd.read_csv(CITY_DATA[city])
    
    df['Start Time'] = pd.to_datetime(df['Start Time'])  # Assign start time dataframe

    # extract month and day of week from Start Time to create new columns
    df['month'] = df['Start Time'].dt.month
    df['day_of_week'] = df['Start Time'].dt.weekday_name
    df['hour'] = df['Start Time'].dt.hour
    
    
    if month != 'all':
        # use the index of the months list to get the corresponding int
        months = ['january', 'february', 'march', 'april', 'may', 'june']
        month = months.index(month) + 1

        # filter by month to create the new dataframe
        df = df[df['month'] == month]

    # filter by day of week if applicable
    if day != 'all':
        # filter by day of week to create the new dataframe
        df = df[df['day_of_week'] == day.title()]
    return df


def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # TO DO: display the most common month
    common_month = df['month'].mode()[0]
    print("most common month is {}".format(common_month))

    # TO DO: display the most common day of week
    common_day = df['day_of_week'].mode()[0]
    print("most common day of the week is {}".format(common_day))

    # TO DO: display the most common start hour
    common_hour = df['hour'].mode()[0]
    print("most common hour is {}".format(common_hour))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)


def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # TO DO: display most commonly used start station
    common_start_station = df['Start Station'].mode()[0]
    print("most commonly used start station is {}".format(common_start_station))

    # TO DO: display most commonly used end station
    common_end_station = df['End Station'].mode()[0]
    print("most commonly used end station is {}".format(common_end_station))

    # TO DO: display most frequent combination of start station and end station trip
   
    df['Common Trip'] = df['Start Station'] +' and '+ df['End Station']
    common_trip = df['Common Trip'].mode()[0]
    print("most frequent comination of start station and end station is {}".format(common_trip))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)


def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # TO DO: display total travel time
    travel_time = df['Trip Duration'].sum()
    print("total travel time is {}".format(travel_time))

    # TO DO: display mean travel time
    mean_travel_time = df['Trip Duration'].mean()
    print("Mean travel time is {} ".format(mean_travel_time))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)


def user_stats(df):
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # TO DO: Display counts of user types
    user_type = df['User Type'].value_counts()
    print("counts of user types {}".format(user_type))

    # TO DO: Display counts of gender
    try:
        gender_counts = df['Gender'].value_counts()
        print("counts of gender {}".format(gender_counts))
    except:
        print("Gender statistics not found")
    # TO DO: Display earliest, most recent, and most common year of birth
    try:         
        earliest_yob = df['Birth Year'].min()
        print("{} is earliest year of birth".format(earliest_yob))          
    except:
        print("Birth year statistics not found")
    
    try:
        latest_yob = df['Birth Year'].max()
        print("the most recent year of birth is {}".format(latest_yob))          
    except:
        print("Birth year statistics not found")
              
    try:          
        common_yob = df['Birth Year'].mode()
        print("mosy common year of birth is {}".format(common_yob))
    except:
        print("Birth year statistics not found")
    
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)
    
def show_data(df):
    #display 5 rows for user
    x = 0
    request_user = input('Would you like to see 5 rows of raw data? Please type yes or no:\n').lower()

    while (x < df['Start Time'].count() and request_user != 'no'):
        print(df.iloc[x:x+5])
        x += 5

        request_more = input('\nIf you would like to see 5 more rows, please yes or no:\n').lower()
        if request_more != 'yes':
            break
    

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)
        
        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)     
        show_data(df)
        
        

        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break


if __name__ == "__main__":
	main()
