import csv

from IPython.core.display import HTML, display
from ipy_table import render, make_table, set_column_style

from city_data_parsing import (
    logger,
    flpd_data_paths,
    get_columns,
    FIRST,
    LNG,
    LAT,
    BASEDIR,
    CITATION
)

(
    accident_csv,
    accident_json,
    citation_csv,
    citation_json,
) = flpd_data_paths  # imported

"""
Explanation: Jupyter notebook example of how to quickly sift through data.
This is a sample of the technique I used to quickly get through large amounts of unfamiliar data at the Code for Fort Lauderdale hackathon.
Jupyter notebooks support over 40 different kernels including Ruby, Node.js, and R which means you can run another language's code inside of a Jupyter notebook.
Don't wonder if you should learn Python or another language. Learn Python and another language. Python plays well with others.
End of explanation
"""


def get_headers(csv_file=citation_csv):
    with open(csv_file) as csvfile:
        reader = reader = csv.DictReader(csvfile)
        for row in reader:
            return list(row.keys())

"""
Explanation: A function for getting the headers from a csv file.
End of explanation
"""


def get_data(csv_file=citation_csv):
    """Lazily return data row as a dictionary from csv file.
    :param csv_file: path to csv file
    :returns: data row as dictionary
    """
    with open(csv_file) as csvfile:
        reader = reader = csv.DictReader(csvfile)
        for row in reader:
            yield row  # yield instead of return makes this a generator

def get_first_item():
    for item in get_data():
        return item

"""
Explanation: A generator for reading csv files and restrieving the data lazily.
End of explanation
"""


headers = get_headers()
logger.debug(headers)

(
    CITATION_CHARGE,
) = (
    'Citation Charge',
)

"""
Explanation: headers for the citation data
End of explanation
"""


# create a (unique) set of citations from all the data
citations = list({datum[CITATION_CHARGE] for datum in get_data()})
citations.sort()
logger.debug(citations)

"""
Explanation: All the citations in the citations file.
End of explanation
"""


citation_counts = [
    (
        len([datum[CITATION_CHARGE] 
             for datum in get_data()
             if datum[CITATION_CHARGE] == citation]), 
        citation.lower() or "NONE SPECIFIED".lower()
    ) for citation in citations
]

# add headers
citation_counts = [('Count', 'Citation', ), ] + citation_counts
# create table with make_table
make_table(citation_counts)
# apply some styles to the table after it is created
set_column_style(0, width='100', bold=True, color='hsla(225, 80%, 94%, 1)')
set_column_style(1, width='100')



"""
Explanation: List comprehension for counting number of citations.
End of explanation
"""


# render the table
display(HTML(render()._repr_html_()))


"""
Explanation: HTML of counts and citations displayed directly in the Jupyter notebook.
End of explanation
"""


