# Copyright (C) 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Request Handler for /main endpoint."""

__author__ = 'alainv@google.com (Alain Vongsouvanh)'


import io
import jinja2
import logging
import os
import webapp2
import random

from google.appengine.api import memcache
from google.appengine.api import urlfetch

import httplib2
from apiclient import errors
from apiclient.http import MediaIoBaseUpload
from apiclient.http import BatchHttpRequest
from oauth2client.appengine import StorageByKeyName

from model import Credentials
import util


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

class Hearty(object):
  def __init__(self):
    self.heart_rate = random.randrange(40,135,1)
    self.step_count = random.randrange(2000,28000,1)
    self.active_minutes = random.randrange(17,132,1)


class HeartyHandler(webapp2.RequestHandler):
  """Request Handler for the main endpoint."""

  def _render_template(self, message=None):
    """Render the main page template."""
    template_values = {'userId': self.userid,
                       'hearty': self.hearty }
    if message:
      template_values['message'] = message
    # self.mirror_service is initialized in util.auth_required.
    try:
      template_values['contact'] = self.mirror_service.contacts().get(
        id='python-quick-start').execute()
    except errors.HttpError:
      logging.info('Unable to find Python Quick Start contact.')

    timeline_items = self.mirror_service.timeline().list(maxResults=3).execute()
    template_values['timelineItems'] = timeline_items.get('items', [])

    subscriptions = self.mirror_service.subscriptions().list().execute()
    for subscription in subscriptions.get('items', []):
      collection = subscription.get('collection')
      if collection == 'timeline':
        template_values['timelineSubscriptionExists'] = True
      elif collection == 'locations':
        template_values['locationSubscriptionExists'] = True

    template = jinja_environment.get_template('templates/hearty.html')
    self.response.out.write(template.render(template_values))

  @util.auth_required
  def get(self):
    """Render the main page."""
    # Get the flash message and delete it.
    message = memcache.get(key=self.userid)
    memcache.delete(key=self.userid)
    self.hearty = Hearty()
    self._render_template(message)

  @util.auth_required
  def post(self):
    """Execute the request and render the template."""
    operation = self.request.get('operation')
    # Dict of operations to easily map keys to methods.
    operations = {
        'insertHeartyData': self._insert_hearty_item
    }
    if operation in operations:
      message = operations[operation]()
    else:
      message = "I don't know how to " + operation
    # Store the flash message for 5 seconds.
    memcache.set(key=self.userid, value=message, time=5)
    self.redirect('/hearty')

  def _insert_hearty_item(self):
      """Insert a Hearty.io timeline item."""
      logging.info('Inserting hearty timeline item')

      bundle_id = `random.random()`

      body = {
          'notification': {'level': 'DEFAULT'},
          'text': 'Hearty.io python',
          'isBundleCover': True,
          'bundleId': bundle_id
      }
      heart_rate = self.request.get('heart_rate')
      step_count = self.request.get('step_count')
      active_minutes = self.request.get('active_minutes')

      body_a = {
          'text': 'Heart Rate: ' + heart_rate,
          'bundleId': bundle_id
      }
      body_b = {
          'text': 'Steps: ' + step_count,
          'bundleId': bundle_id
      }
      body_c = {
          'text': 'Active Minutes: ' + active_minutes,
          'bundleId': bundle_id
      }

      media_link = util.get_full_url(self, "/static/images/hearty_640x360.png")
      resp = urlfetch.fetch(media_link, deadline=20)
      media = MediaIoBaseUpload(
          io.BytesIO(resp.content), mimetype='image/png', resumable=True)

      # self.mirror_service is initialized in util.auth_required.
      self.mirror_service.timeline().insert(body=body, media_body=media).execute()
      self.mirror_service.timeline().insert(body=body_a).execute()
      self.mirror_service.timeline().insert(body=body_b).execute()
      self.mirror_service.timeline().insert(body=body_c).execute()
      return  'A timeline item has been inserted.'


HEARTY_ROUTES = [
    ('/hearty', HeartyHandler)
]
