#!/usr/bin/env python

import csv
import logging
import sys

from api.weather_underground_api import WeatherUnderground


logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

sys.path.append('/Users/lorenamesa/Desktop/pyten/lib/python2.7/site-packages/')

weather_underground = WeatherUnderground(key=None)

current_weather = weather_underground.get_current_weather_for_city(city="Chicago", state="IL")

with open("/Users/lorenamesa/Desktop/pytennessee/weather_data.csv", "ab") as csvdata:
    if current_weather:
        logging.info("Writing weather data...")
        wr = csv.writer(csvdata, dialect='excel')
        wr.writerow(current_weather.__dict__.values())  # windchill,temp,local_epoch,wind_display,weather,location,percipitation_within_hr,feels_like,temp_display
user_timeline = twitter.get_user_timeline(requested_time=requested_time, user_id=None, screen_name="cta")

if user_timeline:
    logging.info("Writing tweets for cta timeline data...")

    for tweet in user_timeline:
        try:
            db.query("INSERT INTO tweets (requested_time, tweet_id, text, created_at) " +
             'VALUES ({0}, {1}, "{2}", "{3}")'.format(tweet.requested_time,
                                                    tweet.tweet_id,
                                                    tweet.text,
                                                    tweet.created_at))
        except IntegrityError as e:
            logger.info("Skipping tweet_id {0} already in DB".format(tweet.tweet_id))

weather_underground = WeatherUnderground(key=None)

current_weather = weather_underground.get_current_weather_for_city(requested_time=requested_time, city="Chicago", state="IL")

if current_weather:
    logging.info("Writing weather data...")

    db.query("INSERT INTO weather (requested_time, location, temperature, feels_like, weather, windchill, percipitation_within_hour) " +
             "VALUES ({0}, '{1}', {2}, {3}, '{4}', '{5}', '{6}')".format(current_weather.requested_time,
                                                                         current_weather.location,
                                                                         current_weather.temperature,
                                                                         current_weather.feels_like,
                                                                         current_weather.weather,
                                                                         current_weather.windchill,
                                                                         current_weather.percipitation_within_hour))