"""A shortcut method to generate geojson file from csv results summary
"""
from __future__ import print_function
import os
import sys

#import numpy as np
import pandas as pd
import geojson

import locale
from locale import atof
locale.setlocale(locale.LC_NUMERIC, '')


if __name__ == '__main__':
    # Load csv file with results
    source_dir = os.path.dirname(os.path.abspath(__file__))
    input_file = os.path.join(source_dir, 'InstagramStatesDataCollect.csv')
    input_df = pd.read_csv(input_file, header=0, skipfooter=1)
    # Gotta strip commans to convert Posts column to number
    input_df['Posts'] = input_df['Posts'].str.replace(',','').astype(int)

    input_df['AhocorasickPerK'] = \
        (1000 * input_df['Ahocorasick partial'] / input_df['Posts']).round(1)
    input_df['TextClassifiedPerK'] = \
        (1000 * input_df['Text-based Classification'] / input_df['Posts']).round(1)

    print(input_df)

    # Load states geometry file
    shared_dir = os.path.join(source_dir, os.pardir, 'shared')
    geostates_filename = os.path.join(shared_dir, 'shapefile_50_states.geojson')

    with open(geostates_filename) as inp:
        geo = geojson.load(inp)
        if geo.get('type') != 'FeatureCollection':
            raise Exception('geojson_states_filename not a FeatureCollection')
        input_feature_collection = geo.get('features')
        print('Input geojson has %d features' % len(input_feature_collection))

    # Build a dictionary of the input feature collection (state geometry)
    input_dict = dict()
    for feature in input_feature_collection:
        properties = feature.get('properties', {})
        name = properties.get('name')
        if not name:
            logging.error('input feature missing name')
            continue
        input_dict[name] = feature

    # Build output features, using geometry in input_dict
    output_feature_list = list()
    for index,row in input_df.iterrows():
        #print('row[State]: {}'.format(row['State']))
        input_feature = input_dict.get(row['State'])
        if input_feature is None:
            print('input geometry has no feature named {} (skipping)'
                .format(index))
            continue

        # Instantiate geojson feature
        geometry = input_feature.get('geometry')
        geo_properties = row.to_dict()
        output_feature = geojson.Feature(
            geometry=geometry, properties=geo_properties)
        output_feature_list.append(output_feature)

    output_feature_collection = geojson.FeatureCollection(output_feature_list)

    # Write feature collection
    output_filename = 'summary.geojson'
    with open(output_filename, 'w') as f:
        geojson.dump(output_feature_collection, f)
        f.write('\n')
        print('Wrote {}'.format(output_filename))
