import json, facebook, re
from mngSettings import getSetting
from commas import *

PATTERNS = {   
    "NUM": "\AF\(([1-9]\d*|0)\) = ([1-9]\d*|0)\Z" ,
    "NC" : "\AF\(([1-9]\d{,2}(?:,\d{3})*|0)\) = ([1-9]\d{,2}(?:,\d{3})*|0)\Z" }
COMPILES = { k:re.compile(v) for k,v in PATTERNS.items() }

COMMAS = getSetting("commas")
COMMENTS = getSetting("comments")
TKNCURR_PATH = getSetting("tokenpath")

def NumericFields(msg):
    # Receives post message msg
    # Returns tuple (n,Fn) where...
    # "n" is the iteration counter
    # "Fn" is the iteration value
    # or returns None if mismatched
    assert(type(msg)==type("")),"Message isn't string"
    for k,c in COMPILES.items():
      result = c.match(msg)
      if c.match(msg) != None:
        assert(k in ["NUM","NC"]),"Pattern unrecognized"
        if k == "NUM":
          return [ int(v) for v in result.groups() ]
        elif k == "NC":
          return [ nwc2num(v) for v in result.groups() ]
        else:
          return None
    return None

def IsBotMessage(msg):
    # Considers every pattern
    # there is and tells if
    # message msg was generated by
    # bot (returns True) or
    # by admin (returns False)
    assert(type(msg)==type("")),"Message isn't string"
    return NumericFields(msg)!=None

def FormatMessage(n,fn):
    # Receives iteration n and iteration value fn
    # Returns formatted post message string
    # depending on the value of setting 'commas'
    assert(type(n)==type(0)),"Counter isn't number"
    assert(type(fn)==type(0)),"Iteration value isn't number"
    if COMMAS == "true":
      return "F({}) = {}".format(num2nwc(n),num2nwc(fn))
    else:
      return "F({}) = {}".format(n,fn)

def FibonacciBot(event, context):
    # Main function
    # Parameters are ignored
    # No return value
    print("Bot running...")
    token = ""
    try:
      f = open(TKNCURR_PATH,"r")
      token = f.readline()
      f.close()
    except IOError:
      print("Could not read token file.")
      return

    graph = facebook.GraphAPI(access_token=token)
    valid_posts = []
    print("Gathering last two iterations...")
    posts = graph.get_connections("me","feed")["data"]
    for p in posts:
      if len(valid_posts)>= 2:
        break
      if ("message" in p and IsBotMessage(p["message"]) ):
        valid_posts.append(p)
             
    i = {}
    
    print("Calculating current iteration...")
    if( len(valid_posts) == 0 ):
      i = { "counter": 0 , "value": 1 }
    elif( len(valid_posts) == 1 ):
      i = { "counter": 1 , "value": 1 }
    else:
      s = [ p["message"] for p in valid_posts ]
      f = [ NumericFields(m) for m in s ]
      i = { "counter": f[0][0] + 1 , "value": f[0][1] + f[1][1] }
      assert(f[0][0]==f[1][0]+1),"Counter jump detected"
        
    post_msg = FormatMessage( i["counter"], i["value"] )
        
    try:
        post = graph.put_photo(open("bar.png","rb"), message=post_msg)
        print("Post published: \""+post_msg[:40]+"...\".")
        print("ID: "+post["id"])
        if COMMENTS == "true":
          from comments import getComment
          try:
            comment_msg = getComment( i["counter"] , i["value"] )
            comment = graph.put_comment(post["post_id"],comment_msg)
            print("Comment published: \""+comment_msg[:40]+"...\".")
            print("ID: "+comment["id"])
          except facebook.GraphAPIError:
            print("An error occurred while trying to comment post")
            return
    except facebook.GraphAPIError:
        print("An error occurred while trying to post to feed.")
        return
        
    return

import json, facebook, re
from mngSettings import getSetting
from commas import *

PATTERNS = {   
    "NUM": "\AF\(([1-9]\d*|0)\) = ([1-9]\d*|0)\Z" ,
    "NC" : "\AF\(([1-9]\d{,2}(?:,\d{3})*|0)\) = ([1-9]\d{,2}(?:,\d{3})*|0)\Z" }
COMPILES = { k:re.compile(v) for k,v in PATTERNS.items() }

COMMAS = getSetting("commas")
COMMENTS = getSetting("comments")
TKNCURR_PATH = getSetting("tokenpath")

def NumericFields(msg):
    # Receives post message msg
    # Returns tuple (n,Fn) where...
    # "n" is the iteration counter
    # "Fn" is the iteration value
    # or returns None if mismatched
    assert(type(msg)==type("")),"Message isn't string"
    for k,c in COMPILES.items():
      result = c.match(msg)
      if c.match(msg) != None:
        assert(k in ["NUM","NC"]),"Pattern unrecognized"
        if k == "NUM":
          return [ int(v) for v in result.groups() ]
        elif k == "NC":
          return [ nwc2num(v) for v in result.groups() ]
        else:
          return None
    return None

def IsBotMessage(msg):
    # Considers every pattern
    # there is and tells if
    # message msg was generated by
    # bot (returns True) or
    # by admin (returns False)
    assert(type(msg)==type("")),"Message isn't string"
    return NumericFields(msg)!=None

def FormatMessage(n,fn):
    # Receives iteration n and iteration value fn
    # Returns formatted post message string
    # depending on the value of setting 'commas'
    assert(type(n)==type(0)),"Counter isn't number"
    assert(type(fn)==type(0)),"Iteration value isn't number"
    if COMMAS == "true":
      return "F({}) = {}".format(num2nwc(n),num2nwc(fn))
    else:
      return "F({}) = {}".format(n,fn)

def FibonacciBot(event, context):
    # Main function
    # Parameters are ignored
    # No return value
    print("Bot running...")
    token = ""
    try:
      f = open(TKNCURR_PATH,"r")
      token = f.readline()
      f.close()
    except IOError:
      print("Could not read token file.")
      return

    graph = facebook.GraphAPI(access_token=token)
    valid_posts = []
    print("Gathering last two iterations...")
    posts = graph.get_connections("me","feed")["data"]
    for p in posts:
      if len(valid_posts)>= 2:
        break
      if ("message" in p and IsBotMessage(p["message"]) ):
        valid_posts.append(p)
             
    i = {}
    
    print("Calculating current iteration...")
    if( len(valid_posts) == 0 ):
      i = { "counter": 0 , "value": 1 }
    elif( len(valid_posts) == 1 ):
      i = { "counter": 1 , "value": 1 }
    else:
      s = [ p["message"] for p in valid_posts ]
      f = [ NumericFields(m) for m in s ]
      i = { "counter": f[0][0] + 1 , "value": f[0][1] + f[1][1] }
      assert(f[0][0]==f[1][0]+1),"Counter jump detected"
        
    post_msg = FormatMessage( i["counter"], i["value"] )
        
    try:
        post = graph.put_photo(open("bar.png","rb"), message=post_msg)
        print("Post published: \""+post_msg[:40]+"...\".")
        print("ID: "+post["id"])
        if COMMENTS == "true":
          from comments import getComment
          try:
            comment_msg = getComment( i["counter"] , i["value"] )
            comment = graph.put_comment(post["post_id"],comment_msg)
            print("Comment published: \""+comment_msg[:40]+"...\".")
            print("ID: "+comment["id"])
          except facebook.GraphAPIError:
            print("An error occurred while trying to comment post")
            return
    except facebook.GraphAPIError:
        print("An error occurred while trying to post to feed.")
        return
        
    return

# Receives post message msg # Returns tuple (n,Fn) where... # "n" is the iteration counter # "Fn" is the iteration value # or returns None if mismatched # Considers every pattern # there is and tells if # message msg was generated by # bot (returns True) or # by admin (returns False) # Receives iteration n and iteration value fn # Returns formatted post message string # depending on the value of setting 'commas' # Main function # Parameters are ignored # No return value