#!/usr/bin/python
# -*- coding: utf-8 -*-
## forward message to standard output and email
## simple fillter
## TODO: digest message
from messenger import Skype, FacebookMessenger
import keyring
import utils
import trollius
from trollius import From
import functools
import sys
from datetime import datetime

cfg = utils.parseConfig()
if cfg == False:
    print("Please check your config file, normally it is config.yml")
    sys.exit(0)
#give empty string will disable email function
emailAddress = cfg['general']['emailaddress']
#only send email if message has a word in bellow list
#leave empty list will disable this filter
strFilter = cfg['general']['filterList']

## get data from keyring to re-used
facebookMessengerCookies = keyring.get_password('messagesReceiver', 'facebookMessengerCookies')
FMusername = keyring.get_password('messagesReceiver', 'FMusername')
FMpassword = keyring.get_password('messagesReceiver', 'FMpassword')
FMToken = keyring.get_password('messagesReceiver', 'FacebookMessengerToken')

fm = FacebookMessenger(FMusername, FMpassword, FMToken, facebookMessengerCookies)
if fm.cookies == None or fm.token == None:
    fm.login()
    print("Login...")

# trigger for Ctrl + C to quit
quit = False

def getFM():
    seq = 0
    print("Facebook running...")
    while not quit:
        msg = fm.pull(seq)
        #print msg
        if msg == "502":
            print("Connection error, trying again...")
            continue
        if msg.get('reason') == 110:
            print("110 - refresh")
            fm.reset()
            fm.login()
        seq = msg.get('seq', 0)
        messages = utils.FMParse(msg)
        commandList = ['girl', 'fun']
        if not messages:
            continue
        for sender, receiver, message, thread_url, is_thread in messages:
            if is_thread:
                print("Thread: %s - %s" % (receiver, thread_url))
            allow_thread = cfg.get('FM').get('allow_bot')
            command = utils.getBotCommand(message)
            print allow_thread
            print(thread_url in allow_thread)
            print(command)
            if command != None and command in commandList and thread_url in allow_thread:
                msg = utils.getBotAnswer(command)
                print(msg)
                print(thread_url)
                if is_thread:
                    direct = False
                else:
                    direct = True
                r = fm.post(thread_url, msg.encode('utf-8'), direct=direct)
                print r
                if r == 404:
                    fm.reset()
                    fm.login()
                    r = fm.post(thread_url, msg.encode('utf-8'), direct=direct)
            if not utils.doFillter(strFilter, message.encode('utf-8')):
                continue
            print("sending email")
            utils.sendMsgEmail("FM", sender, receiver, message, emailAddress)
            print("sent email")
            utils.printMsg("FM", sender, receiver, message)

        #test_client = cfg['FM']['khanhpro']
        #r = fm.post(test_client, "", direct=True)

## get message with two threads
## asyncio to catch KeyboardInterrupt
@trollius.coroutine
def getMsg():
    loop = trollius.get_event_loop()
    FMThread = loop.run_in_executor(None, functools.partial(getFM))
    yield From(FMThread)

loop = trollius.get_event_loop()

## add trigger for quit (not really interrupt)
try:
    loop.run_until_complete(getMsg())
except KeyboardInterrupt:
    quit = True
