#!/usr/bin/env python
import bitso # put the package from https://github.com/bitsoex/bitso-py on your python env
import sys
from pprint import pprint
from  scarpkg import logStart, logStop, logMsg, Log, get_info, Bot, images
import __main__
import os
import telegram
import argparse
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
                          ConversationHandler)
import logging
import ipgetter
import tempfile

#Steps to converstations
#STATUS, CANCEL, CONFIRMCANCEL =  range(3)
#OPERATION, SETPRICE, MXN, CONFIRMATION, SETORDER = range(5)


logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

def get_my_args():

    parser = argparse.ArgumentParser()
    parser.add_argument("-v","--verbose", help="Set verbose to True",action="store_true")
    parser.add_argument("-l","--log", help="Set logpath, default=/tmp",default="/tmp")
    parser.add_argument("-I","--variables", help="File with variables info default {0}/.variales.yaml".format(os.environ['HOME']),default=os.environ['HOME']+"/.variables.yaml")
    args = parser.parse_args()

    return args





def status(bot, update):
    log.msg("Command : status")
    if str(update.message.chat_id) == telegram_id:
        msg = "Capturando imagenes"

        bot.send_message(chat_id=update.message.chat_id, text=msg)
        #bot.send_photo(chat_id=update.message.chat_id, photo=open("/Users/Scar/Pictures/mariokog.gif","rb"))
        try:
            #log.msg("grabing")
            img = images.grab("172.31.10.61",8081)
            #print img
            #log.msg("genraate tmp file")
            tmp_img = tempfile.TemporaryFile()
            #log.msg("write to tmp")
            tmp_img.write(img)
            #log.msg("seek0")
            tmp_img.seek(0)
            #log.msg("send")
            bot.send_message(chat_id=update.message.chat_id, text="mandar")
            bot.send_photo(chat_id=update.message.chat_id, photo=tmp_img)
            #log.msg("sent")
            bot.send_message(chat_id=update.message.chat_id, text="mandado")
            #log.msg("close")

            tmp_img.close()
            log.msg("del")
            del(tmp_img)
        except:
            bot.sendMessage(chat_id, 'Error capturando camara 1' )

        try :
            img = images.grab2("172.31.10.136",8081)
            tmp_img = tempfile.TemporaryFile()
            tmp_img.write(img)
            tmp_img.seek(0)
            bot.send_photo(chat_id=update.message.chat_id, photo=tmp_img)
            tmp_img.close()
            del(tmp_img)
        except:
            bot.sendMessage(chat_id, 'Error capturando camara 2' )


        #bot.send_photo(chat_id=update.message.chat_id, photo=open("/Users/scar/Pictures/20160619_213121724_iOS.jpg",'rb'))
        log.msg("Status sent")
    else:
        bot.send_message(chat_id=update.message.chat_id, text="Hi I'm a bot")
        log.msg("Got a message from {0}, chat id {1}, username {2}".format(update.message.from_user.first_name,
                                                                        update.message.chat_id, update.message.from_user.username))

def get_ip(bot, update):
    log.msg("Command : get_ip")
    if str(update.message.chat_id) == telegram_id:
        myip = ipgetter.myip()
        if myip:
            #bot.sendMessage(chat_id, myip )
            bot.send_message(chat_id=update.message.chat_id, text=myip)
        else:
            bot.sendMessage(chat_id, 'Unable to get ip' )
            bot.send_message(chat_id=update.message.chat_id, text='Unable to get ip')
        log.msg("ip sent")
    else:
        bot.send_message(chat_id=update.message.chat_id, text="Hi I'm a bot")
        log.msg("Got a message from {0}, chat id {1}, username {2}".format(update.message.from_user.first_name,
                                                                        update.message.chat_id, update.message.from_user.username))

def echo(bot, update):
    log.msg("Function: echo ")
    bot.send_message(chat_id=update.message.chat_id, text=update.message.text)
    log.msg("Got a message from {0}, chat id {1}, username {2}".format(update.message.from_user.first_name,
                                                                        update.message.chat_id, update.message.from_user.username))
    log.msg("MSG : {0}".format(update.message.text))

def unknown(bot, update):
    log.msg("Function: unknown")
    bot.send_message(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command.")
    log.msg("Got a message from {0}, chat id {1}, username {2}".format(update.message.from_user.first_name,
                                                                        update.message.chat_id, update.message.from_user.username))


def error(bot, update, error):
    """Log Errors caused by Updates."""
    log.msg("Function : error")
    log.msg('Update {0} caused error {1}'.format(update, error))


if __name__ == "__main__":
    args = get_my_args()
    log = Log(args.log,args.verbose)
    INFO = get_info(args.variables)
    #bitso_key=INFO['bitso']['key']
    #bitso_secret=INFO['bitso']['secret']
    telegram_id=INFO['ScarBot']['id']
    telegram_bot=INFO['ScarBot']['token']
    my_user=INFO['ScarBot']['user']

    #Create bot
    cmd=[]
    oid=''
    updater = Updater(token=telegram_bot)
    dispatcher = updater.dispatcher

    #status get camaras
    status_handler = CommandHandler('camaras', status,filters=Filters.chat(username=my_user))
    dispatcher.add_handler(status_handler)

    status_handler = CommandHandler('ip', get_ip,filters=Filters.chat(username=my_user))
    dispatcher.add_handler(status_handler)


    ##echo handler
    echo_handler = MessageHandler(Filters.text, echo) # echo messages for all users
    dispatcher.add_handler(echo_handler)

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO

    #Unkown handler
    unknown_handler = MessageHandler(Filters.command, unknown) # for unknown commands
    dispatcher.add_handler(unknown_handler)
    # start bot
    dispatcher.add_error_handler(error) # log errors
    updater.start_polling() # start bot
    updater.idle() # allow kill bot


