import csv
from datetime import datetime

input_file = "Chicago_Traffic_Tracker_-_Historical_Congestion_Estimates_by_Segment_-_2018-Current.csv"
output_file = "data_State_2022.csv"

s_street_name = "State"
s_from_name = "Congress"
s_to_name = "Roosevelt"

my_row = ['TIME', 'SPEED', 'STREET', 'DIRECTION', 'FROM_STREET', 'TO_STREET', 'HOUR', 'DAY_OF_WEEK', 'MONTH']
my_columns = []

counter = 0
error = 0

with open(input_file, 'r', newline='') as file_read:
    with open(output_file, 'w', newline='') as file_write:
        file_reader = csv.reader(file_read)
        file_writer = csv.writer(file_write)
        header = next(file_reader)

        for index in range(len(header)):
            if header[index] in my_row:
                my_columns.append(index)
        file_writer.writerow(my_row)

        for row in file_reader:
            try:
                s = str(row[0])
                time = datetime.strptime(s, '%m/%d/%Y %I:%M:%S %p')

                speed = int(row[2])
                street_name = str(row[3])
                from_name = str(row[5])
                to_name = str(row[6])

                if (time.date().year == 2022) and (speed != -1) and (street_name == s_street_name) and \
                        ((from_name == s_from_name) and (to_name == s_to_name)):
                    row_list = []
                    for index in my_columns:
                        row_list.append(row[index])

                    counter = counter + 1
                    print(counter, error)

                    file_writer.writerow(row_list)
            except:
                error = error+1
                continue
