# Path: db.py
# def create_db_connnection():
# def getConfig():
# 
# Path: lib/decorators.py
# def database_conn(func):
#     """Provides db cursor for decorated func."""
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         db = connect(host=db_config['host'],
#                              user=db_config['username'],
#                              passwd=db_config['password'],
#                              db=db_config['database'])
#         with closing(db.cursor()) as cursor:
#             result = func(cursor, *args, **kwargs)
#         return result
#     return wrapper
# 
# def memoize(func):
#     """Simple caching decorator.
# 
#     Puts result of the call to decorated function into
#     dictionary with key equals to positional args
#     supplied to function. Next call with the same
#     args will result in cache lookup instead of real
#     function call. Will not work with unhashable
#     positional args.
# 
#     Adopted from here:
#     https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
#     """
#     cache = {}
# 
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         try:
#             if args not in cache:
#                 cache[args] = func(*args, **kwargs)
#             return cache[args]
#         except TypeError:
#             return func(*args, **kwargs)
# 
#     return wrapper
# 
# Path: utils.py
# def build_tbpl_link(record):
#     # TODO: is branch valid?
#     tbpl_branch = record.branch.split('-Non-PGO')[0]
#     if tbpl_branch == 'Firefox':
#         treeherder_repo = 'mozilla-central'
#     else:
#         treeherder_repo = tbpl_branch.lower()
# 
#     vals = get_revision_range(treeherder_repo, record.keyrevision)
# 
#     link = ''
#     if vals:
#         params = []
# 
#         tbpl_platform = settings.TBPL_PLATFORMS[record.platform]
#         tbpl_test = settings.TBPL_TESTS[record.test]['jobname']
#         tbpl_tree = settings.TBPL_TREES[record.branch]
# 
#         if 'OSX' in tbpl_platform:
#             tbpl_tree = tbpl_tree.split(' pgo')[0]
# 
#         params.append(('repo', treeherder_repo))
#         params.append(('fromchange', vals[0]))
#         params.append(('tochange', vals[1]))
#         params.append(('filter-searchStr', '%s %s talos %s' % (tbpl_platform, tbpl_tree, tbpl_test)))
#         link = settings.TREEHERDER_URL
#         delim = '?'
#         for key, value in params:
#             link = "%s%s%s=%s" % (link, delim, key, value)
#             if delim == '?':
#                 delim = '&'
#         link = link.replace(' ', '%20')
# 
#     return link


import time
import os
import re
import settings
from datetime import datetime, timedelta
from db import app, getConfig
from lib.decorators import database_conn, memoize
from utils import build_tbpl_link
pmap['OSX10.105'] = 'MacOSX 10.10.5'
pmap['Android'] = 'Android 4.0.4'


@database_conn
def findDuplicates(db_cursor, branch, tests, platforms):
   for test in tests:
       for platform in platforms:
           query = "select id,platform,test,status,percent,keyrevision from alerts where branch='%s' and test='%s' and platform='%s' and percent<0" % (branch, test, pmap[platform])
           db_cursor.execute(query)
           rows = db_cursor.fetchall()
           data = {}
           for row in rows:
               if row[5] not in data:
                   data[row[5]] = row
               else:
                   old = data[row[5]]
                   if old[4] == row[4]:
                       if old[3] == 'Duplicate':
                           print "deleting:"
                           print old
                           db_cursor.execute("delete from alerts where id=%s" % old[0])
                           data[row[5]] = row
                       elif row[3] == 'Duplicate':
                           print "deleting:"
                           print row
                           db_cursor.execute("delete from alerts where id=%s" % row[0])




# Path: db.py
# def create_db_connnection():
# def getConfig():
# 
# Path: lib/decorators.py
# def database_conn(func):
#     """Provides db cursor for decorated func."""
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         db = connect(host=db_config['host'],
#                              user=db_config['username'],
#                              passwd=db_config['password'],
#                              db=db_config['database'])
#         with closing(db.cursor()) as cursor:
#             result = func(cursor, *args, **kwargs)
#         return result
#     return wrapper
# 
# def memoize(func):
#     """Simple caching decorator.
# 
#     Puts result of the call to decorated function into
#     dictionary with key equals to positional args
#     supplied to function. Next call with the same
#     args will result in cache lookup instead of real
#     function call. Will not work with unhashable
#     positional args.
# 
#     Adopted from here:
#     https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
#     """
#     cache = {}
# 
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         try:
#             if args not in cache:
#                 cache[args] = func(*args, **kwargs)
#             return cache[args]
#         except TypeError:
#             return func(*args, **kwargs)
# 
#     return wrapper
# 
# Path: utils.py
# def build_tbpl_link(record):
#     # TODO: is branch valid?
#     tbpl_branch = record.branch.split('-Non-PGO')[0]
#     if tbpl_branch == 'Firefox':
#         treeherder_repo = 'mozilla-central'
#     else:
#         treeherder_repo = tbpl_branch.lower()
# 
#     vals = get_revision_range(treeherder_repo, record.keyrevision)
# 
#     link = ''
#     if vals:
#         params = []
# 
#         tbpl_platform = settings.TBPL_PLATFORMS[record.platform]
#         tbpl_test = settings.TBPL_TESTS[record.test]['jobname']
#         tbpl_tree = settings.TBPL_TREES[record.branch]
# 
#         if 'OSX' in tbpl_platform:
#             tbpl_tree = tbpl_tree.split(' pgo')[0]
# 
#         params.append(('repo', treeherder_repo))
#         params.append(('fromchange', vals[0]))
#         params.append(('tochange', vals[1]))
#         params.append(('filter-searchStr', '%s %s talos %s' % (tbpl_platform, tbpl_tree, tbpl_test)))
#         link = settings.TREEHERDER_URL
#         delim = '?'
#         for key, value in params:
#             link = "%s%s%s=%s" % (link, delim, key, value)
#             if delim == '?':
#                 delim = '&'
#         link = link.replace(' ', '%20')
# 
#     return link


# Path: doquery.py
import time
import os
import re
import settings
from datetime import datetime, timedelta
from db import app, getConfig
from lib.decorators import database_conn, memoize
from utils import build_tbpl_link

pmap['OSX10.105'] = 'MacOSX 10.10.5'
pmap['Android'] = 'Android 4.0.4'


@database_conn
def findDuplicates(db_cursor, branch, tests, platforms):
   for test in tests:
       for platform in platforms:
           query = "select id,platform,test,status,percent,keyrevision from alerts where branch='%s' and test='%s' and platform='%s' and percent<0" % (branch, test, pmap[platform])
           db_cursor.execute(query)
           rows = db_cursor.fetchall()
           data = {}
           for row in rows:
               if row[5] not in data:
                   data[row[5]] = row
               else:
                   old = data[row[5]]
                   if old[4] == row[4]:
                       if old[3] == 'Duplicate':
                           print "deleting:"
                           print old
                           db_cursor.execute("delete from alerts where id=%s" % old[0])
                           data[row[5]] = row
                       elif row[3] == 'Duplicate':
                           print "deleting:"
                           print row
                           db_cursor.execute("delete from alerts where id=%s" % row[0])




@database_conn