#!/usr/bin/python


from __future__ import print_function
from contextlib import closing

import threading
import configparser
import re

import getopt
import time
import pymysql
import sys
import traceback

from geoInfo.MaxMindRepo import MaxMindRepo

def usage(msg="Usage"):
    print(msg)
    print('python3 '+sys.argv[0]+' -d RIBS_LOCATION [-h]')
    sys.exit(2)

def current_time():
    return int(time.time()),time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())

class Logger():

    def __init__(self,logfilename):
        self.lock = threading.RLock()
        self.logfilename = logfilename
    
    def print_log(self,msg):
        self.lock.acquire()
        try:
            
            #Log file
            logfile = open(self.logfilename,'a+')

            _,localtime=current_time()
            time='['+localtime+']  '
            print(time,'INFO:',msg,file=logfile)
            logfile.close()

        finally:
            self.lock.release()


            
def dbpush_asn_geo(db,asn,location): 
    #print("In dbpush_asn_geo")
    with closing( db.cursor() ) as cur: 
        try:
            cur.execute("select ASNLocation from ASNGeo where ASN = '{0}' and GeoDate='{1}'".format(asn,geoDate))
            row=cur.fetchone()
            if row is not None: #We have seen this ASN-GeoDate before
                countries=re.sub('[{}]','',row[0])
                tmpSet=countries.split(',')
                for entry in tmpSet:
                   et=re.sub('[\"|\'| ]','',entry)
                   location.add(et)
                #print(str(location))
                cur.execute('update ASNGeo set ASNLocation = "{0}" where GeoDate = "{1}"'.format(str(location),geoDate))
            else:
                cur.execute("insert into ASNGeo(GeoDate,ASN,ASNLocation) values (%s,%s,%s)",(geoDate,asn,str(location)))
        except:
           raise Exception('Insert to ASNGeo Failed')

def query_get_distinct_asn(db):
    with closing( db.cursor() ) as cur:
        toReturn=[]
        try:
            cur.execute("SELECT distinct OriginAS FROM BGPPrefixGeo where GeoDate= '{0}'".format(geoDate))
            row=cur.fetchone()
            while row is not None:
                if '}' not in row[0] and '{' not in row[0]: #We will ignore Group of Origin ASes 
                    toReturn.extend(row)
                row=cur.fetchone()
     
        except Exception:
           raise Exception('Select Query Distinct ASN Failed')

        if toReturn:
            return toReturn
        else:
            return False


def query_asn_locations(db,asn):
    toReturn=set()
    with closing( db.cursor() ) as cur:
        try:
            cur.execute('SELECT distinct PrefixLocation FROM BGPPrefixGeo WHERE OriginAS = "{0}" and GeoDate="{1}"'.format(asn,geoDate))