from celery import Celery
from sqlalchemy.orm import scoped_session

from settings import Config
config = Config()

from models import Reservation, Flight, FlightLeg, FlightLegLocation
from db import Database
from sw_checkin_email import *

celery = Celery('tasks')
celery.config_from_object('celery_config')

if config["STORE_DATABASE"]:
  if config["HEROKU_DB"]:
    db = Database(heroku=True)
  elif config["POSTGRES_DB"] != '':
    db = Database(postgres=config["POSTGRES_DB"])
  else:
    db = Database(sqlite=config["SQLITE_DB"])
else:
  db = Database()

@celery.task(default_retry_delay=config["RETRY_INTERVAL"], max_retries=config["MAX_RETRIES"])
def check_in_flight(reservation_id, flight_id):
  session = scoped_session(db.session_factory)
  flight = session.query(Flight).get(flight_id)
  if flight.success:
    print "Skipping flight %d. Already checked in at %s" % (flight_id, flight.position)
    return

  reservation = session.query(Reservation).get(reservation_id)

  (position, boarding_pass) = getBoardingPass(reservation)

  if position:
    return check_in_success(reservation, flight, boarding_pass, position, session)
    session.remove()
  else:
    print 'FAILURE. Scheduling another try in %d seconds' % config["RETRY_INTERVAL"]
    session.remove()
    raise check_in_flight.retry(args=(reservation_id, flight_id))

@celery.task()
def update_all_reservation_activity():
  print "[Task] Updating all reservations..."
  session = scoped_session(db.session_factory)
  reservations = session.query(Reservation).filter_by(active = True).all()
  count = 0
  for res in reservations:
    for (i, flight) in enumerate(res.flights):
      flight_time = time_module.mktime(flight.legs[0].depart.dt_utc.utctimetuple()) - time_module.timezone
      if flight_time < time_module.time():
        flight.active = False
    res.isReservationActive()
    if not res.active:
      count += 1
    session.commit()
  session.remove()
  print "[Task] Marked %d reservations as inactive..." % count

@celery.task()
def delete_inactive_old_reservations():
  session = scoped_session(db.session_factory)
  reservations = session.query(Reservation).filter_by(active = False).all()
  # Delete reservations and associated relationships
  res_count          = 0
  flight_count       = 0
  leg_count          = 0
  for res in reservations:
    for flight in res.flights:
      for leg in flight.legs:
        session.delete(leg.depart)
        session.delete(leg.arrive)
        session.delete(leg)
        leg_count += 1
      session.delete(flight)
      flight_count += 1
    session.delete(res)
    res_count += 1

  session.remove()
  print "[Task] Deleted %d reservations, %d flights, %d flight legs, and %d leg locations" % (res_count, flight_count, leg_count, leg_count*2)

@@ -2182,129 +2182,17 @@
 )%0A  
-# Delete reservations and associated relationships%0A  res_count          = 0%0A  flight_count       = 0%0A  leg_count         
+res_count
  = 0
@@ -2354,112 +2354,8 @@
 ve)%0A
-        session.delete(leg)%0A        leg_count += 1%0A      session.delete(flight)%0A      flight_count += 1%0A
     
@@ -2456,63 +2456,12 @@
 ions
-, %25d flights, %25d flight legs, and %25d leg locations
 %22 %25 
-(
 res_
@@ -2469,44 +2469,5 @@
 ount
-, flight_count, leg_count, leg_count*2)
 %0A

update delete_inactive_old_reservations for cascade relationships