import webapp2
import cgi
import datetime
from datetime import datetime
import urllib
import jinja2
import os
import json
import models

from google.appengine.api import users
from models import *

def parseDateString(string):
    """To parse strings like this: 2013-04-12T10:29:00Z
       We only actually pull out the date part for now."""
    return datetime.strptime(string.split('T')[0], "%Y-%m-%d")

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class FavouriteHandler(webapp2.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user:
            seriesName = self.request.get('series')

            # Store fact that this series name is to be downloaded in future
            series = Series(user_key(user))
            series.name = seriesName
            series.blocked = False
            series.put()
            
            # And also download all current episodes matching this series
            query = Episode.all().ancestor(user_key(user)).filter('seriesName =', seriesName)
            episodes = []
            for episode in query.run():
                episode.status = 'download'
                episodes.append(episode)
            db.put(episodes)
            self.response.out.write("ok: Marked %s episodes for download" % len(episodes))
        else:
            self.response.out.write("error: Not logged in")

class BlockHandler(webapp2.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user:
            seriesName = self.request.get('series')

            # Store fact that this series name is to be ignored in future
            series = Series(user_key(user))
            series.name = seriesName
            series.blocked = True
            series.put()
            
            # And also ignore all current episodes matching this series
            query = Episode.all().ancestor(user_key(user)).filter('seriesName =', seriesName)
            episodes = []
            for episode in query.run():
                episode.status = 'ignore'
                episodes.append(episode)
            db.put(episodes)
            self.response.out.write("ok: Ignored %s episodes" % len(episodes))
        else:
            self.response.out.write("error: Not logged in")

class DownloadHandler(webapp2.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user:
            pid = self.request.get('pid')
            query = Episode.all().ancestor(user_key(user)).filter('pid =', pid)
            episode = query.get()
            if episode:
                episode.status = 'download'
                episode.put()
                self.response.out.write("ok: Added to download queue")
            else:
                self.response.out.write("error: Episode not found")
        else:
            self.response.out.write("error: Not logged in")