from datetime import datetime

import endpoints

from protorpc import messages
from protorpc import message_types
from protorpc import remote

from google.appengine.ext import ndb
from google.appengine.api import memcache
from google.appengine.api import taskqueue

from models import BooleanMessage
from models import ConflictException
from models import StringMessage

from models import Conference
from models import ConferenceForm
from models import ConferenceForms
from models import ConferenceQueryForms

from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import TeeShirtSize

from models import Session
from models import SessionForm
from models import SessionByTypeForm
from models import SessionBySpeakerForm
from models import SessionForms

from utils import getUserId

from settings import WEB_CLIENT_ID


EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
DEFAULTS = {"city": "Default City",
            "maxAttendees": 0,
            "seatsAvailable": 0,
            "topics": ["Default", "Topic"]}
FIELDS = {'CITY': 'city',
          'TOPIC': 'topics',
          'MONTH': 'month',
          'MAX_ATTENDEES': 'maxAttendees'}
OPERATORS = {'EQ':   '=',
             'GT':   '>',
             'GTEQ': '>=',
             'LT':   '<',
             'LTEQ': '<=',
             'NE':   '!='}
CONF_GET_REQUEST = endpoints.ResourceContainer(
    message_types.VoidMessage,
    websafeConferenceKey=messages.StringField(1),
)
SESSION_GET_REQUEST = endpoints.ResourceContainer(
    message_types.VoidMessage,
    SessionKey=messages.StringField(1),
)
MEMCACHE_ANNOUNCEMENTS_KEY = 'announcements'
MEMCACHE_FEATUREDSPEAKER_KEY = 'featuredSpeaker'


@endpoints.api(name='conference',
               version='v1',
               allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
               scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
    """Conference API v0.1"""

# - - - Helper functions - - - - - - - - - - - - - - - - - - -

    @staticmethod
    def _cacheAnnouncement():
        """Create Announcement & assign to memcache; used by
        memcache cron job & putAnnouncement().
        """
        # Get conferences with 5 seats or less available
        confs = Conference.query(ndb.AND(
            Conference.seatsAvailable <= 5,
            Conference.seatsAvailable > 0)
        ).fetch(projection=[Conference.name])
        if confs:
            # If there are almost sold out conferences,
            # format announcement and set it in memcache
            announcement = '%s %s' % (
                'Last chance to attend! The following conferences '
                'are nearly sold out:',
                ', '.join(conf.name for conf in confs))
            memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement)
        else:
            # If there are no almost sold out conferences,
            # delete the memcache announcements entry
            announcement = ""
            memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY)
        return announcement

    @ndb.transactional(xg=True)
    def _conferenceRegistration(self, request, reg=True):
        """Register or unregister user for selected conference."""
        retval = None
        prof = self._getProfileFromUser()
        # Get conference, check that it exists
        wsck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=wsck).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)
        # Register
        if reg:
            # Check if user already registered otherwise add
            if wsck in prof.conferenceKeysToAttend:
                raise ConflictException(
                    "You have already registered for this conference")
            # Check if seats available
            if conf.seatsAvailable <= 0:
                raise ConflictException(
                    "There are no seats available.")
            # Register user, take away one seat
            prof.conferenceKeysToAttend.append(wsck)
            conf.seatsAvailable -= 1
            retval = True
        # Unregister
        else:
            # Check if user already registered
            if wsck in prof.conferenceKeysToAttend:
                # Unregister user, add back one seat
                prof.conferenceKeysToAttend.remove(wsck)
                conf.seatsAvailable += 1
                retval = True
            else:
                retval = False
        # Write things back to the datastore & return
        prof.put()
        conf.put()
        return BooleanMessage(data=retval)

    def _copyConferenceToForm(self, conf, displayName):
        """Copy relevant fields from Conference to ConferenceForm."""
        cf = ConferenceForm()
        for field in cf.all_fields():
            if hasattr(conf, field.name):
                # Convert Date to date string, just copy others
                if field.name.endswith('Date'):
                    setattr(cf, field.name, str(getattr(conf, field.name)))
                else:
                    setattr(cf, field.name, getattr(conf, field.name))
            elif field.name == "websafeKey":
                setattr(cf, field.name, conf.key.urlsafe())
        if displayName:
            setattr(cf, 'organizerDisplayName', displayName)
        cf.check_initialized()
        return cf

    def _copyProfileToForm(self, prof):
        """Copy relevant fields from Profile to ProfileForm."""
        pf = ProfileForm()
        for field in pf.all_fields():
            if hasattr(prof, field.name):
                # Convert t-shirt string to Enum, just copy others
                if field.name == 'teeShirtSize':
                    setattr(pf, field.name, getattr(TeeShirtSize,
                                                    getattr(prof, field.name)))
                elif field.name == 'sessionKeysWishlist':
                    setattr(pf, field.name, str(getattr(prof, field.name)))
                else:
                    setattr(pf, field.name, getattr(prof, field.name))
        pf.check_initialized()
        return pf

    def _copySessionToForm(self, session):
        """Copy relevant fields from Conference to ConferenceForm."""
        sf = SessionForm()
        for field in sf.all_fields():
            # Convert date and startTime to strings, just copy others
            if field.name in ('date', 'startTime'):
                setattr(sf, field.name, str(getattr(session, field.name)))
            else:
                setattr(sf, field.name, getattr(session, field.name))
        sf.check_initialized()
        return sf

    def _createConferenceObject(self, request):
        """Create or update Conference object,
           returning ConferenceForm/request."""
        # Preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        # Check that a conference name was provided
        if not request.name:
            raise endpoints.BadRequestException("Conference 'name'"
                                                "field required")
        # Copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        del data['websafeKey']
        del data['organizerDisplayName']
        # Add default values for missing
        for df in DEFAULTS:
            if data[df] in (None, []):
                data[df] = DEFAULTS[df]
                setattr(request, df, DEFAULTS[df])
        # Convert dates from strings to Date objects and
        # set month based on start_date
        if data['startDate']:
            data['startDate'] = datetime.strptime(data['startDate'][:10],
                                                  "%Y-%m-%d").date()
            data['month'] = data['startDate'].month
        else:
            data['month'] = 0
        if data['endDate']:
            data['endDate'] = datetime.strptime(data['endDate'][:10],
                                                "%Y-%m-%d").date()
        # Set seatsAvailable to be same as maxAttendees on creation
        # both for data model & outbound Message
        if data["maxAttendees"] > 0:
            data["seatsAvailable"] = data["maxAttendees"]
            setattr(request, "seatsAvailable", data["maxAttendees"])
        # Make Profile Key from user ID
        p_key = ndb.Key(Profile, user_id)
        # Allocate new Conference ID with Profile key as parent
        c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
        # Make Conference key from ID
        c_key = ndb.Key(Conference, c_id, parent=p_key)
        data['key'] = c_key
        data['organizerUserId'] = request.organizerUserId = user_id
        # Create Conference & return (modified) ConferenceForm
        Conference(**data).put()
        taskqueue.add(params={'email': user.email(),
                              'conferenceInfo': repr(request)},
                      url='/tasks/send_confirmation_email')
        return request

    def _createSessionObject(self, request):
        # Check that user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # Check that conference and session names are provided
        if not request.name or not request.conference:
            raise endpoints.BadRequestException("Session 'name' and"
                                                "'conference' fields required")
        # Copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}
        # Convert dates from strings to Date objects
        if data['date']:
            data['date'] = datetime.strptime(data['date'], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'],
                                                  "%H:%M").time()
        # Make Key and get parent Conference
        user_id = getUserId(user)
        c_key = ndb.Key(Conference, request.conference)
        conference = Conference.query(Conference.name == request.conference)
        conference = conference.get()
        # Check that conference exists
        if not conference:
            raise endpoints.BadRequestException("Conference does not exist.")
        # Check that user created this conference
        if conference.organizerUserId != user_id:
            raise endpoints.BadRequestException("Only conference organizer"
                                                "can create sessions.")
        # Allocate new Session ID with Conference key as parent
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        # Make Session key from Session ID
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key
        # create Conference & return (modified) ConferenceForm
        Session(**data).put()
        # Add task to check if this speaker should be featured
        taskqueue.add(params={'speaker': request.speaker,
                              'conference': request.conference},
                      url='/tasks/check_featured_speaker')
        return request

    def _doProfile(self, save_request=None):
        """Get user Profile and return to user, possibly updating it first."""
        # Get user Profile
        prof = self._getProfileFromUser()
        # Process user-modifyable fields if save_request
        if save_request:
            for field in ('displayName', 'teeShirtSize'):
                if hasattr(save_request, field):
                    val = getattr(save_request, field)
                    if val:
                        setattr(prof, field, str(val))
            # Write profile to datastore
            prof.put()
        return self._copyProfileToForm(prof)

    def _formatFilters(self, filters):
        """Parse, check validity and format user supplied filters."""
        formatted_filters = []
        inequality_field = None
        for f in filters:
            filtr = {field.name: getattr(f, field.name)
                     for field in f.all_fields()}
            try:
                filtr["field"] = FIELDS[filtr["field"]]
                filtr["operator"] = OPERATORS[filtr["operator"]]
            except KeyError:
                raise endpoints.BadRequestException("Filter contains invalid"
                                                    "field or operator.")
            # Every operation except "=" is an inequality
            if filtr["operator"] != "=":
                # check if inequality operation has been used in previous
                # filters and disallow the filter if inequality was performed
                # on a different field before. track the field on which the
                # inequality operation is performed
                if inequality_field and inequality_field != filtr["field"]:
                    raise endpoints.BadRequestException("Inequality filter is"
                                                        "allowed on only one"
                                                        "field.")
                else:
                    inequality_field = filtr["field"]
            formatted_filters.append(filtr)
        return (inequality_field, formatted_filters)

    def _getProfileFromUser(self):
        """Return user Profile from datastore or create new one."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(),
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()
        return profile

    def _getQuery(self, request):
        """Return formatted query from the submitted filters."""
        q = Conference.query()
        inequality_filter, filters = self._formatFilters(request.filters)
        # If exists, sort on inequality filter first
        if not inequality_filter:
            q = q.order(Conference.name)
        else:
            q = q.order(ndb.GenericProperty(inequality_filter))
            q = q.order(Conference.name)
        for filtr in filters:
            if filtr["field"] in ["month", "maxAttendees"]:
                filtr["value"] = int(filtr["value"])
            formatted_query = ndb.query.FilterNode(filtr["field"],
                                                   filtr["operator"],
                                                   filtr["value"])
            q = q.filter(formatted_query)
        return q

    @staticmethod
    def _updateFeaturedSpeaker(speaker, conference):
        """Update featured speaker in cache."""
        # If speaker of created session already has a session at this
        # conference, make them the featured speaker
        sessions = Session.query(ndb.AND(Session.speaker == speaker,
                                         Session.conference == conference))
        if sessions.count() > 1:
            memcache.set(MEMCACHE_FEATUREDSPEAKER_KEY, speaker)
        return speaker

# - - - Endpoints - - - - - - - - - - - - - - - - - - -

    @endpoints.method(SESSION_GET_REQUEST, SessionForm,
                      path='conference/{SessionKey}/addSessionToWishlist',
                      http_method='POST', name='addSessionToWishlist')
    def addSessionToWishlist(self, request):
        """Add session to user's wishlist."""
        # Get Session from Key and check that it exists
        s_key = request.SessionKey
        session = ndb.Key(urlsafe=s_key).get()
        if not session:
            raise endpoints.NotFoundException(
                'No session found with key: %s' % s_key)
        # Append Key to Profile's session wishlist
        prof = self._getProfileFromUser()
        prof.sessionKeysWishlist.append(s_key)
        prof.put()
        return self._copySessionToForm(session)

    @endpoints.method(ConferenceForm, ConferenceForm,
                      path='conference',
                      http_method='POST', name='createConference')
    def createConference(self, request):
        """Create new conference."""
        return self._createConferenceObject(request)

    # open only to the organizer of the conference
    @endpoints.method(SessionForm, SessionForm,
                      path='session',
                      http_method='POST', name='createSession')
    def createSession(self, request):
        """Create new session."""
        return self._createSessionObject(request)

    @endpoints.method(message_types.VoidMessage, StringMessage,
                      path='conference/announcement/get',
                      http_method='GET', name='getAnnouncement')
    def getAnnouncement(self, request):
        """Return Announcement from memcache."""
        announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY)
        if not announcement:
            announcement = ""
        return StringMessage(data=announcement)

    @endpoints.method(CONF_GET_REQUEST, ConferenceForm,
                      path='conference/{websafeConferenceKey}',
                      http_method='GET', name='getConference')
    def getConference(self, request):
        """Return requested conference (by websafeConferenceKey)."""
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)
        prof = conf.key.parent().get()
        return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))

    @endpoints.method(message_types.VoidMessage, ConferenceForms,
                      path='getConferencesCreated',
                      http_method='POST', name='getConferencesCreated')
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        # Make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # Make profile key
        p_key = ndb.Key(Profile, getUserId(user))
        # Create ancestor query for this user
        conferences = Conference.query(ancestor=p_key)
        # Get the user profile and display name
        prof = self._getProfileFromUser()
        displayName = getattr(prof, 'displayName')
        return ConferenceForms(items=[self._copyConferenceToForm(conf,
                                                                 displayName)
                                      for conf in conferences])

    @endpoints.method(CONF_GET_REQUEST, SessionForms,
                      path='conference/{websafeConferenceKey}/sessions',
                      http_method='POST', name='getConferenceSessions')
    def getConferenceSessions(self, request):
        """Return sessions by conference."""
        # Check that conference name was provided
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("Must specify conference!")
        # Get conference and check that it exists
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)
        # Get all Sessions for this Conference and check that there are > 0
        sessions = Session.query(Session.conference == conf.name)
        if sessions.count() == 0:
            raise endpoints.NotFoundException('No sessions for '
                                              'this conference.')
        return SessionForms(items=[self._copySessionToForm(session)
                                   for session in sessions])

    @endpoints.method(SessionBySpeakerForm, SessionForms,
                      path='{speaker}/sessions',
                      http_method='POST',
                      name='getConferenceSessionsBySpeaker')
    def getConferenceSessionsBySpeaker(self, request):
        """Return sessions by speaker."""
        # Check that speaker was provided
        if not request.speaker:
            raise endpoints.BadRequestException("Must specify speaker!")
        # Get all Sessions with this speaker and check that there are > 0
        sessions = Session.query().filter(Session.speaker == request.speaker)
        if sessions.count() == 0:
            raise endpoints.NotFoundException('No sessions with this speaker.')
        return SessionForms(items=[self._copySessionToForm(session)
                                   for session in sessions])

    @endpoints.method(SessionByTypeForm, SessionForms,
                      path='conference/{websafeConferenceKey}/{typeOfSession}'
                           '/sessions',
                      http_method='POST', name='getConferenceSessionsByType')
    def getConferenceSessionsByType(self, request):
        """Return sessions by session type."""
        # Make sure Conference and typeOfSession were specified
        if not request.websafeConferenceKey or not request.typeOfSession:
            raise endpoints.BadRequestException("Must specify conference "
                                                "and session type!")
        # Get conference and check that it exists
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)
        # Get all Sessions of typeOfSession and check that there are > 0
        sessions = Session.query(Session.conference == conf.name)\
            .filter(Session.typeOfSession == request.typeOfSession)
        if sessions.count() == 0:
            raise endpoints.NotFoundException('No sessions of this type.')
        return SessionForms(items=[self._copySessionToForm(session)
                                   for session in sessions])

    @endpoints.method(message_types.VoidMessage, ConferenceForms,
                      path='conferences/attending',
                      http_method='GET', name='getConferencesToAttend')
    def getConferencesToAttend(self, request):
        """Get list of conferences that user has registered for."""
        prof = self._getProfileFromUser()
        conferenceKeys = prof.conferenceKeysToAttend
        c_keys = [ndb.Key(urlsafe=c) for c in conferenceKeys]
        conferences = ndb.get_multi(c_keys)
        return ConferenceForms(items=[self._copyConferenceToForm(conf, "")
                                      for conf in conferences])

    @endpoints.method(message_types.VoidMessage, StringMessage,
                      path='featuredSpeaker/get',
                      http_method='GET', name='getFeaturedSpeaker')
    def getFeaturedSpeaker(self, request):
        """Return featured speaker from memcache."""
        featuredSpeaker = memcache.get(MEMCACHE_FEATUREDSPEAKER_KEY)
        if not featuredSpeaker:
            featuredSpeaker = ""
        return StringMessage(data=featuredSpeaker)

    @endpoints.method(message_types.VoidMessage, ProfileForm,
                      path='profile',
                      http_method='GET', name='getProfile')
    def getProfile(self, request):
        """Return user profile."""
        return self._doProfile()

    @endpoints.method(message_types.VoidMessage, SessionForms,
                      path='session/wishlist',
                      http_method='POST', name='getSessionsInWishlist')
    def getSessionsInWishlist(self, request):