import StringIO
import json
import logging
import random
import urllib
import urllib2
import time
import math
import re

import requests
# import requests_toolbelt.adapters.appengine

# Use the App Engine Requests adapter. This makes sure that Requests uses
# URLFetch.
# requests_toolbelt.adapters.appengine.monkeypatch()

# sending images
# try:
#     from PIL import Image
# except:
#     pass
# import multipart
#
# # standard app engineimports
# from google.appengine.api import urlfetch
# from google.appengine.ext import deferred
# from google.appengine.ext import ndb
# from google.appengine.api.taskqueue import TaskRetryOptions
# import webapp2

TOKEN = '363749995:AAEMaasMVLSPqSuSr1MiEFcgQH_Yn88hlbg'

BASE_URL = 'https://api.telegram.org/bot' + TOKEN + '/'

#urlfetch.set_default_fetch_deadline(60)

ALERTS = set()

#
# def deffered_track_pair_price(pair, current_price, target_price, chat_id, message_id):
#     alert_key = (pair, target_price)
#     logging.info("Checking price alert..{} if {}".format(pair, target_price))
#     kraken = KrakenExchange()
#     ticker = kraken.getTicker(pair=ASSETPAIRS[pair])
#     askPrice = float(ticker['Ask Price'][0])
#     bidPrice = float(ticker['Bid Price'][0])
#     live_price = (askPrice + bidPrice) / 2
#     target_price = float(target_price)
#     if current_price < target_price and live_price >= target_price:
#         ALERTS.remove(alert_key)
#         reply_message(
#             chat_id=chat_id,
#             message_id=message_id,
#             msg="{} just hit {}!".format(
#                 pair, live_price
#             )
#         )
#     elif current_price > target_price and live_price <= target_price:
#         ALERTS.remove(alert_key)
#         reply_message(
#             chat_id=chat_id,
#             message_id=message_id,
#             msg="{} just hit {}!".format(
#                 pair, live_price
#             )
#         )
#     else:
#         raise Exception("Alert not hit, fail task so it is retried")
#
#
# def track_pair_price(pair, current_price, target_price, chat_id, message_id):
#     ALERTS.add(
#         (pair, target_price)
#     )
#
#     deferred.defer(
#         deffered_track_pair_price,
#         pair, current_price, target_price, chat_id, message_id,
#         _retry_options=TaskRetryOptions(
#             min_backoff_seconds=60,
#             task_age_limit=86400
#         ) # 1 day
#     )
#
#
# # ================================
#
# class EnableStatus(ndb.Model):
#     # key name: str(chat_id)
#     enabled = ndb.BooleanProperty(indexed=False, default=False)
#
#
# # ================================
#
# def setEnabled(chat_id, yes):
#     es = EnableStatus.get_or_insert(str(chat_id))
#     es.enabled = yes
#     es.put()
#
# def getEnabled(chat_id):
#     es = EnableStatus.get_by_id(str(chat_id))
#     if es:
#         return es.enabled
#     return False
#
#
# # ================================
#
# class MeHandler(webapp2.RequestHandler):
#     def get(self):
#         urlfetch.set_default_fetch_deadline(60)
#         self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))
#
#
# class GetUpdatesHandler(webapp2.RequestHandler):
#     def get(self):
#         urlfetch.set_default_fetch_deadline(60)
#         self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))
#
#
# class SetWebhookHandler(webapp2.RequestHandler):
#     def get(self):
#         urlfetch.set_default_fetch_deadline(60)
#         url = self.request.get('url')
#         if url:
#             self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'setWebhook', urllib.urlencode({'url': url})))))
#
#
# def reply_message(chat_id, message_id, msg=None, img=None):
#     if msg:
#         resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
#             'chat_id': str(chat_id),
#             'text': msg.encode('utf-8'),
#             'disable_web_page_preview': 'true',
#             'reply_to_message_id': str(message_id),
#             'parse_mode': 'Markdown'
#         })).read()
#     elif img:
#         resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
#             ('chat_id', str(chat_id)),
#             ('reply_to_message_id', str(message_id)),
#         ], [
#             ('photo', 'image.jpg', img),
#         ])
#     else:
#         logging.error('no msg or img specified')
#         resp = None
#
#     logging.info('send response:')
#     logging.info(resp)


class WebhookHandler(webapp2.RequestHandler):
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        update_id = body['update_id']
        try:
            message = body['message']
        except:
            message = body['edited_message']
        message_id = message.get('message_id')
        date = message.get('date')
        text = message.get('text')
        fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']

        def reply(msg=None, img=None):
            reply_message(msg=msg, img=img, chat_id=chat_id, message_id=message_id)

        if not text:
            logging.info('no text')
            return

        if text.startswith('/'):
            text_kraken = re.sub('(\/btc)', '/xbt', text)
            text_kraken = re.sub('(btc$)', 'xbt', text)