import pickle
import threading

from bmconfigparser import BMConfigParser
import state

knownNodesLock = threading.Lock()
knownNodes = {}

knownNodesTrimAmount = 2000

def saveKnownNodes(dirName = None):
    if dirName is None:
        dirName = state.appdata
    with knownNodesLock:
        with open(dirName + 'knownnodes.dat', 'wb') as output:
            pickle.dump(knownNodes, output)

def increaseRating(peer):
    increaseAmount = 0.1
    maxRating = 1
    with knownNodesLock:
        for stream in knownNodes.keys():
            try:
                knownNodes[stream][peer]["rating"] = min(knownNodes[stream][peer]["rating"] + increaseAmount, maxRating)
            except KeyError:
                pass

def decreaseRating(peer):
    decreaseAmount = 0.1
    minRating = -1
    with knownNodesLock:
        for stream in knownNodes.keys():
            try:
                knownNodes[stream][peer]["rating"] = max(knownNodes[stream][peer]["rating"] - decreaseAmount, minRating)
            except KeyError:
                pass

def trimKnownNodes(recAddrStream = 1):
    if len(knownNodes[recAddrStream]) < BMConfigParser().get("knownnodes", "maxnodes"):
        return
    with knownNodesLock:
        oldestList = sorted(knownNodes[recAddrStream], key=lambda x: x['lastseen'])[:knownNodesTrimAmount]
        for oldest in oldestList:
            del knownNodes[recAddrStream][oldest]

[((7, 17, 7, 33), 'threading.Lock', 'threading.Lock', ({}, {}), '()', False, 'import threading\n'), ((17, 12, 17, 43), 'pickle.dump', 'pickle.dump', ({(17, 24, 17, 34): 'knownNodes', (17, 36, 17, 42): 'output'}, {}), '(knownNodes, output)', False, 'import pickle\n'), ((40, 40, 40, 56), 'bmconfigparser.BMConfigParser', 'BMConfigParser', ({}, {}), '()', False, 'from bmconfigparser import BMConfigParser\n')]