import csv, json, operator

TIMESTAMP      = 0
SKIRT_TYPE     = 1
SKIRT_LENGTH   = 2
SKIRT_WEIGHT   = 3
SKIRT_STRETCHY = 4
WORN_WITH      = 5
REASON         = 6
GENDER         = 7
COUNTRY        = 8

# ===========================================================
# Export data for js graph tool
# ===========================================================
def export_to_graph_tool(name, output_data):

    lut_idx = 0;
    colour_lut = [
        '#287233',
        '#EAE6CA',
        '#FF7514',
        '#3E5F8A',
        '#B32821',
        '#CFD3CD',
        '#82898F',
        '#C7B446',
        '#F44611',
        '#3B83BD',
        '#DE4C8A',
        '#FF2301',
        '#6D3F5B',
        '#EFA94A',
        '#F75E25',
    ]

    labels  = []
    values  = []
    colours = []

    sorted_data = sorted(output_data.items(), key=operator.itemgetter(1))
    sorted_data.reverse()

    for x in sorted_data: 
        k = x[0]
        v = x[1]

        labels.append(k)
        values.append(v)

        colours.append(colour_lut[lut_idx])
        lut_idx += 1;

    return {
      'labels': labels,
      'datasets': [{
        'label': name,
        'data': values,
        'backgroundColor': colours,
        'hoverOffset': 4
      }]
    }



normalised = []

with open('Contra dance skirts.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)


    # Type normalisation for charts
    skirt_type_lut = {
     'Straight / pencil':
         'Straight / pencil',

     'Circle (including square hankey-hem skirts)':
        'Circle',
     'Circle but definitely NOT square hankey-hem. Between knee length and mid-calf.':
        'Circle',

     'double circle!' : 'Double circle!',

     'Swing skirt (half circle)':
         'Half circle',

     "Gathered (including tiered and 'gypsy')":
        'Gathered',

     'Gored': 'Gore / godet',

     'Kilt (traditional or modern / utility)':
        'Kilt',

     "I think it's pleated, but I'm such a non skirt wearing person, I don't have the lingo. It's made by Jenny Horrocks.":
        'Pleated',
     'Pleated':
        'Pleated',

     'Light and swirly':
        'Light and swirly',

     'Heavier and swirly':
        'Light and swirly',

     'Peplum - straight but flows at the bottom':
        'Peplum',

     'Skort':
        'Skort',


     'Many of the above, as long as it has a good twirl!':
        'Anything twirlable',
     'Very twirlable :)':
        'Anything twirlable',
     "I don't have a specific single favorite, the ones I like best are of various specific constructions, but all very full. I will be answering the rest of the questions with an approximate average.":
        'Anything twirlable',
 'Gathered, Circle, and Light and Swirly are my favorites (based on the options listed above)':
        'Anything twirlable',
 'Anything that twirls up & out! (Light and swirly AND circle, and...)':
        'Anything twirlable',
    }



    getner_lut = {
       'Female '           : 'Female',
       'Cis woman'         : 'Female',
       'Cis female'        : 'Female',
       'Female (a robin)'  : 'Female',
       'Woman'             : 'Female',
       'She/her female'    : 'Female',
       'female'            : 'Female',
       'She/her'           : 'Female',
       'Girl'              : 'Female',
       'Robin'             : 'Female',
       'Female-ish'        : 'Female',
       'she/her'           : 'Female',
       'Woman all the way' : 'Female',
       'F'                 : 'Female',
       'Female senior'     : 'Female',
       'Femme'             : 'Female',
       'Fem'               : 'Female',
       'she/her pronouns'  : 'Female',
       'Female (a robin)'  : 'Female',
       'cis female'        : 'Female',
       'Cis-woman'         : 'Female',
       'Femme'             : 'Female',
       'Femme '            : 'Female',
       'Falr'              : 'Female',
       'Female (a robin) ' : 'Female',
       'Female/woman'      : 'Female',
       '💁\u200d♀️'         : 'Female',
       'I identify as female.'        : 'Female',
       'I identify as female'         : 'Female',
       'female, but I dance all roles': 'Female',
 

       'Male '             : 'Male',
       'Heterosexual Male' : 'Male',
       'CIS male'          : 'Male',


       'Non-binary'        : 'Non binary unspecified',
       'Agender, wear skirts in my day to day' : 'Non binary unspecified',

       'female/nonbinary'  : 'Non binary afab',
       'Female/ Agender'   : 'Non binary afab',
       'Queer cis female ' : 'Non binary afab',
       'f, ish'            : 'Non binary afab',
       'Queer cis female ' : 'Non binary afab',

       'Non-binary, amab'  : 'Non binary amab',
       '(amab) agender'    : 'Non binary amab',


       'female (older, queer, non-fem, sporty)': 'Non binary afab',
       'Female, skewing gender nonconforming'  : 'Non binary afab',

        '' : 'not answered',
    };




    # Normalise countries
    country_lut = {
     'American'       : 'USA',
     'United States'  : 'USA',
     'United States ' : 'USA',
     'Us'             : 'USA',
     'US'             : 'USA',
     'US '            : 'USA',
     'usa'            : 'USA',
     'Usa'            : 'USA',
     'Usa '           : 'USA',
     'USA '           : 'USA',
     'U.S.'           : 'USA',
     'USA! USA!'      : 'USA',
     'Uda'            : 'USA',
     'I live in California and Colorado.'            : 'USA',



     'uk'      : 'UK',
     'Uk'      : 'UK',
     'England' : 'UK'

    }


    """
     'Bare legs or leggings, depending on the weather. I usually end up removing the leggings afterway through the dance.': 1,
     'Bare, unless shorts are necessary. ': 1,

     'Basketball shorts? These appear to be different?': 1,
     'Bike shorts underneath': 1,

     'Dance shorts or bare legs, and a slip': 1,
     'Dance shorts, leggings, or bare legs (depending on the weather)': 1,
     'It’s a skort': 1,
     'Sometimes shorts.. sometimes not ': 1,
     'Workout shorts - longer length ': 1,
     'dance shorts': 72,


     'Slip shorts': 1,

     'Bloomer shorts with (occasionally) a net underskirt ': 1,

     'Larger briefs than usual. I never had a use for boxer briefs until I got skirts and people told me my usual underwear was TMI.': 1,
     "men's boxer briefs": 1,
     'Boxer briefs ': 1,
     'Boxers': 1,

     'Briefs': 1,
     'Petite pants. Or slip if needed': 1,

    'An underskirt, which includes both a twirly layer and a modesty skirt(straight)': 1,

     'Half slip': 2,
     'Slip': 1,
     'Slip, it’s the coolest': 1,
     'Straight knee-length slip': 1,
     'High socks with flash': 1,

     'bare legs': 34,
     'bare legs and a slip': 1,
     'bare legs unless skirt is very short or very twirly, then bike shorts, capri leggings or if winter, tights': 1,

     'leggings': 5,
     'Tights': 1,
     'nylons/tights': 1}
    """


    #Table for heavy handed normalisation of 'what with'
    worn_with_heavy_lut = {

        # bare legs
        'Bare legs or leggings, depending on the weather. I usually end up removing the leggings afterway through the dance.':
            'bare legs',
         'Bare, unless shorts are necessary. ':
            'bare legs',
         'bare legs and a slip':
            'bare legs',
         'bare legs unless skirt is very short or very twirly, then bike shorts, capri leggings or if winter, tights':
            'bare legs',
         'Petite pants. Or slip if needed':
            'bare legs',

         'Briefs':
            'bare legs',


         # shorts
         'Basketball shorts? These appear to be different?': 'shorts',
         'Bike shorts underneath'                          : 'shorts',

         'Dance shorts or bare legs, and a slip'           : 'shorts',
         'It’s a skort'                                    : 'shorts',
         'Sometimes shorts.. sometimes not '               : 'shorts',
         'Workout shorts - longer length '                 : 'shorts',
         'dance shorts'                                    : 'shorts',
         'Slip shorts'                                     : 'shorts',
         'Dance shorts, leggings, or bare legs (depending on the weather)':
            'shorts',
         'Bloomer shorts with (occasionally) a net underskirt ':
            'shorts',

         'Larger briefs than usual. I never had a use for boxer briefs until I got skirts and people told me my usual underwear was TMI.':
            'shorts',
         "men's boxer briefs":
            'shorts',
         'Boxer briefs ':
            'shorts',
         'Boxers':
            'shorts',


        # slip
        'An underskirt, which includes both a twirly layer and a a modesty skirt(straight)':
            'slip',
        'Half slip':
            'slip',
        'Slip':
            'slip',
        'Slip, it’s the coolest':
            'slip',
        'Straight knee-length slip':
            'slip',

        # Long socks
        'High socks with flash': 'long socks',


        # Leggings
        'leggings': 'leggings',


        # Tights
        'Tights'        : 'tights',
        'nylons/tights' : 'tights',
    }


    row_i = 0;
    for row in reader:

        # Skip labels
        if row_i == 0:
            row_i += 1
            continue

        row_i += 1


        #normalise worn with
        with_name = ''
        if row[WORN_WITH] in worn_with_heavy_lut:
            with_name = worn_with_heavy_lut[row[WORN_WITH]]
        else:
            with_name = row[WORN_WITH]


        #normalise type
        type_name = ''
        if row[SKIRT_TYPE] in skirt_type_lut:
            type_name = skirt_type_lut[row[SKIRT_TYPE]]
        else:
            type_name = row[SKIRT_TYPE]


        # Normalise gender
        gender_name = ''
        if row[GENDER] in getner_lut:
            gender_name = getner_lut[row[GENDER]]
        else:
            gender_name = row[GENDER]

        #normalise country
        country_name = ''
        if row[COUNTRY] in country_lut:
            country_name = country_lut[row[COUNTRY]]
        else:
            country_name = row[COUNTRY]

        # Assemble result
        normalised.append({
            'timestamp'    : row[TIMESTAMP],
            'type'         : type_name,
            'length'       : row[SKIRT_LENGTH],
            'weight'       : row[SKIRT_WEIGHT],
            'stretchyness' : row[SKIRT_STRETCHY],
            'worn with'    : with_name,
            'reason'       : row[REASON],
            'Gender'       : gender_name,
            'country'      : country_name
        })



#=============================
import pprint


# Tally types
types = {};

for row in normalised:
    type_name = row['type']
    if not type_name in types:
        types[type_name] = 0;

    types[type_name] += 1;


pprint.pprint(
    export_to_graph_tool('Number of answers:', types))




# Tally lengths
lengths = {};

for row in normalised:
    length_name = row['length']
    if not length_name in lengths:
        lengths[length_name] = 0;

    lengths[length_name] += 1;


pprint.pprint(
    export_to_graph_tool('Number of answers:', lengths))



# Tally weights
weights = {};

for row in normalised:
    weight_name = row['weight']
    if not weight_name in weights:
        weights[weight_name] = 0;

    weights[weight_name] += 1;

pprint.pprint(
    export_to_graph_tool('Number of answers:', weights))


# Tally stretch
stretches = {};

for row in normalised:
    stretch_name = row['stretchyness']
    if not stretch_name in stretches:
        stretches[stretch_name] = 0;

    stretches[stretch_name] += 1;


pprint.pprint(
    export_to_graph_tool('Number of answers:', stretches))



# Tally worn with
worn_withs = {};

for row in normalised:
    with_name = row['worn with']
    if not with_name in worn_withs:
        worn_withs[with_name] = 0;

    worn_withs[with_name] += 1;

pprint.pprint(
    export_to_graph_tool('Number of answers:', worn_withs))


# Tally countries
countries = {};

for row in normalised:
    country_name = row['country']
    if not country_name in countries:
        countries[country_name] = 0;

    countries[country_name] += 1;

pprint.pprint(
    export_to_graph_tool('Number of answers:', countries))



# Tally genders
genders = {};

for row in normalised:
    gender_name = row['Gender']
    if not gender_name in genders:
        genders[gender_name] = 0;

    genders[gender_name] += 1;

pprint.pprint(
    export_to_graph_tool('Number of answers:', genders))


# -------------------------------------
# Bin the data based on skirt types
# -------------------------------------
by_type = {}

for row in normalised:
    type_name = row['type']
    if not type_name in by_type:
        by_type[type_name] = [];

    by_type[type_name].append(row)


# -------------------------------------
# Get material weight and thickness preference for each type
# -------------------------------------
weights_and_stretch_by_type = {}

for k, v in by_type.items():

    weights_and_stretch_by_type[k] = {
        'weights'     : {},
        'stretch' : {}
    }
    

    for row in v:
        weight_name = row['weight']
        if not weight_name in weights_and_stretch_by_type[k]['weights']:
            weights_and_stretch_by_type[k]['weights'][weight_name] = 0;

        weights_and_stretch_by_type[k]['weights'][weight_name] += 1;

        # -------------
        stretch_name = row['stretchyness']
        if not stretch_name in weights_and_stretch_by_type[k]['stretch']:
            weights_and_stretch_by_type[k]['stretch'][stretch_name] = 0;

        weights_and_stretch_by_type[k]['stretch'][stretch_name] += 1;

pprint.pprint(weights_and_stretch_by_type)



# ==============================================================
# ==============================================================
# ==============================================================
"""
'Circle': {'stretch': {'not at all stretchy': 23,
                       'slightly stretchy': 16,
                       'very stretchy': 6}}



'Light and swirly': {'stretch': {'not at all stretchy': 24,
                                 'slightly stretchy': 29,
                                 'very stretchy': 3}}


'Gathered': {'stretch': {'not at all stretchy': 8,
                         'slightly stretchy': 2,
                         'very stretchy': 0}}


'Gore / godet': {'stretch': {'not at all stretchy': 4,
                             'slightly stretchy': 3,
                             'very stretchy': 0}}
"""




# ==============================================================
# ==============================================================
# ==============================================================
"""
'Circle': {
            'weights': {'about the same': 19,
                        'heavier': 12,
                        'lighter than t-shirt fabric': 14}},


'Light and swirly': {
                     'weights': {'about the same': 26,
                                 'heavier': 3,
                                 'lighter than t-shirt fabric': 27}},

'Gathered': {
             'weights': {'about the same': 2,
                         'heavier': 1,
                         'lighter than t-shirt fabric': 7}},

'Gore / godet': {
                 'weights': {'about the same': 2,
                             'heavier': 3,
                             'lighter than t-shirt fabric': 2}},
"""






# bin the data based on country,
# See if there are any differences 



for row in normalised:
    print(row['reason'] + '\n')




