# Path: tasks/us/census/tiger.py
# class ShorelineClip(TableTask):
#     '''
#     Clip the provided geography to shoreline.
#     '''
# 
#     # MTFCC meanings:
#     # http://www2.census.gov/geo/pdfs/maps-data/data/tiger/tgrshp2009/TGRSHP09AF.pdf
# 
#     year = IntParameter()
#     geography = Parameter()
# 
#     def version(self):
#         return 10
# 
#     def requires(self):
#         if self.geography == BLOCK:
#             tiger = SimplifiedUnionTigerWaterGeomsByState(year=self.year, geography=self.geography)
#         else:
#             tiger = SimplifiedUnionTigerWaterGeoms(year=self.year, geography=self.geography)
#         return {
#             'data': tiger,
#             'geoms': ClippedGeomColumns(year=self.year),
#             'geoids': GeoidColumns(year=self.year),
#             'attributes': Attributes(),
#             'geonames': GeonameColumns(year=self.year),
#         }
# 
#     def columns(self):
#         return OrderedDict([
#             ('geoid', self.input()['geoids'][self.geography + '_{}'.format(self.year) + GEOID_SHORELINECLIPPED_COLUMN]),
#             ('the_geom', self.input()['geoms'][self.geography + '_{}'.format(self.year) + '_clipped']),
#             ('aland', self.input()['attributes']['aland'])
#         ])
# 
#     def table_timespan(self):
#         return get_timespan(str(self.year))
# 
#     # TODO: https://github.com/CartoDB/bigmetadata/issues/435
#     def targets(self):
#         return {
#             OBSTable(id='.'.join([self.schema(), self.name()])): GEOM_REF,
#         }
# 
#     def populate(self):
#         session = current_session()
# 
#         stmt = ('''INSERT INTO {output}
#                    SELECT
#                      geoid,
#                      ST_Union(ARRAY(
#                        SELECT ST_MakePolygon(ST_ExteriorRing(
#                          (ST_Dump(ST_CollectionExtract(the_geom, 3))).geom
#                        ))
#                      )),
#                      aland
#                    FROM {input}'''.format(
#                     output=self.output().table,
#                     input=self.input()['data'].table), )[0]
#         session.execute(stmt)
# 
# Path: tasks/us/census/acs.py
# class ACSMetaWrapper(MetaWrapper):
# 
#     geography = Parameter()
#     year = Parameter()
#     sample = Parameter()
# 
#     params = {
#         'geography': GEOGRAPHIES,
#         'year': YEARS,
#         'sample': SAMPLES
#     }
# 
#     def tables(self):
#         # no ZCTA for 2010
#         if self.year == '2010' and self.geography == ZCTA5:
#             pass
#         # 1yr sample doesn't have block group or census_tract
#         elif self.sample == SAMPLE_1YR and self.geography in (CENSUS_TRACT, BLOCK_GROUP, BLOCK, ZCTA5):
#             pass
#         else:
#             yield Quantiles(geography=self.geography, year=self.year, sample=self.sample)
# 
# Path: tasks/meta.py
# def current_session():
#     '''
#     Returns the session relevant to the currently operating :class:`Task`, if
#     any.  Outside the context of a :class:`Task`, this can still be used for
#     manual session management.
#     '''
#     return _current_session.get()
# 
# Path: lib/logger.py
# def get_logger(name):
#     '''
#     Obtain a logger outputing to stderr with specified name. Defaults to INFO
#     log level.
#     '''
#     logger = logging.getLogger(name)
#     if LUIGI_LOG_ARG in sys.argv:
#         index = sys.argv.index(LUIGI_LOG_ARG) + 1
#         if len(sys.argv) > index:
#             logger.setLevel(sys.argv[index])
# 
#     return logger


import os
import json
import csv
from luigi import Task, WrapperTask, Parameter
from luigi.local_target import LocalTarget
from tasks.us.census.tiger import ShorelineClip
from tasks.us.census.acs import ACSMetaWrapper
from tasks.meta import current_session
from lib.logger import get_logger


LOGGER = get_logger(__name__)

# TODO Add block level when we have ACS for block
GEOGRAPHY_LEVELS = {'state': 'us.census.tiger.state',
                    'county': 'us.census.tiger.county',
                    'census_tract': 'us.census.tiger.census_tract',
                    'zcta5': 'us.census.tiger.zcta5',
                    'block_group': 'us.census.tiger.block_group',
                    'block': 'us.census.tiger.block'}


class Measurements2CSV(Task):
    geography = Parameter()
    file_name = Parameter()

    def __init__(self, *args, **kwargs):
        super(Measurements2CSV, self).__init__(*args, **kwargs)

    def requires(self):
        return {
            'shorelineclip': ShorelineClip(geography=self.geography, year='2015'),
            'acs5yr': ACSMetaWrapper(geography=self.geography, year='2015', sample='5yr'),

# Path: tasks/us/census/tiger.py
# class ShorelineClip(TableTask):
#     '''
#     Clip the provided geography to shoreline.
#     '''
# 
#     # MTFCC meanings:
#     # http://www2.census.gov/geo/pdfs/maps-data/data/tiger/tgrshp2009/TGRSHP09AF.pdf
# 
#     year = IntParameter()
#     geography = Parameter()
# 
#     def version(self):
#         return 10
# 
#     def requires(self):
#         if self.geography == BLOCK:
#             tiger = SimplifiedUnionTigerWaterGeomsByState(year=self.year, geography=self.geography)
#         else:
#             tiger = SimplifiedUnionTigerWaterGeoms(year=self.year, geography=self.geography)
#         return {
#             'data': tiger,
#             'geoms': ClippedGeomColumns(year=self.year),
#             'geoids': GeoidColumns(year=self.year),
#             'attributes': Attributes(),
#             'geonames': GeonameColumns(year=self.year),
#         }
# 
#     def columns(self):
#         return OrderedDict([
#             ('geoid', self.input()['geoids'][self.geography + '_{}'.format(self.year) + GEOID_SHORELINECLIPPED_COLUMN]),
#             ('the_geom', self.input()['geoms'][self.geography + '_{}'.format(self.year) + '_clipped']),
#             ('aland', self.input()['attributes']['aland'])
#         ])
# 
#     def table_timespan(self):
#         return get_timespan(str(self.year))
# 
#     # TODO: https://github.com/CartoDB/bigmetadata/issues/435
#     def targets(self):
#         return {
#             OBSTable(id='.'.join([self.schema(), self.name()])): GEOM_REF,
#         }
# 
#     def populate(self):
#         session = current_session()
# 
#         stmt = ('''INSERT INTO {output}
#                    SELECT
#                      geoid,
#                      ST_Union(ARRAY(
#                        SELECT ST_MakePolygon(ST_ExteriorRing(
#                          (ST_Dump(ST_CollectionExtract(the_geom, 3))).geom
#                        ))
#                      )),
#                      aland
#                    FROM {input}'''.format(
#                     output=self.output().table,
#                     input=self.input()['data'].table), )[0]
#         session.execute(stmt)
# 
# Path: tasks/us/census/acs.py
# class ACSMetaWrapper(MetaWrapper):
# 
#     geography = Parameter()
#     year = Parameter()
#     sample = Parameter()
# 
#     params = {
#         'geography': GEOGRAPHIES,
#         'year': YEARS,
#         'sample': SAMPLES
#     }
# 
#     def tables(self):
#         # no ZCTA for 2010
#         if self.year == '2010' and self.geography == ZCTA5:
#             pass
#         # 1yr sample doesn't have block group or census_tract
#         elif self.sample == SAMPLE_1YR and self.geography in (CENSUS_TRACT, BLOCK_GROUP, BLOCK, ZCTA5):
#             pass
#         else:
#             yield Quantiles(geography=self.geography, year=self.year, sample=self.sample)
# 
# Path: tasks/meta.py
# def current_session():
#     '''
#     Returns the session relevant to the currently operating :class:`Task`, if
#     any.  Outside the context of a :class:`Task`, this can still be used for
#     manual session management.
#     '''
#     return _current_session.get()
# 
# Path: lib/logger.py
# def get_logger(name):
#     '''
#     Obtain a logger outputing to stderr with specified name. Defaults to INFO
#     log level.
#     '''
#     logger = logging.getLogger(name)
#     if LUIGI_LOG_ARG in sys.argv:
#         index = sys.argv.index(LUIGI_LOG_ARG) + 1
#         if len(sys.argv) > index:
#             logger.setLevel(sys.argv[index])
# 
#     return logger


# Path: tasks/geographica/us/csv.py
import os
import json
import csv
from luigi import Task, WrapperTask, Parameter
from luigi.local_target import LocalTarget
from tasks.us.census.tiger import ShorelineClip
from tasks.us.census.acs import ACSMetaWrapper
from tasks.meta import current_session
from lib.logger import get_logger



LOGGER = get_logger(__name__)

# TODO Add block level when we have ACS for block
GEOGRAPHY_LEVELS = {'state': 'us.census.tiger.state',
                    'county': 'us.census.tiger.county',
                    'census_tract': 'us.census.tiger.census_tract',
                    'zcta5': 'us.census.tiger.zcta5',
                    'block_group': 'us.census.tiger.block_group',
                    'block': 'us.census.tiger.block'}


class Measurements2CSV(Task):
    geography = Parameter()
    file_name = Parameter()

    def __init__(self, *args, **kwargs):
        super(Measurements2CSV, self).__init__(*args, **kwargs)

    def requires(self):
        return {
            'shorelineclip': ShorelineClip(geography=self.geography, year='2015'),
            'acs5yr': ACSMetaWrapper(geography=self.geography, year='2015', sample='5yr'),

            'acs1yr': ACSMetaWrapper(geography=self.geography, year='2015', sample='1yr'),