import sys
import logging
import grafon.constants as constants
from grafon.graphs.plwngraph import PlWNGraph

def get_senses_from_nxgraph(graph):
  """!
  From given graph gets all (if exists) senses from plwordnet. This method uses
  the tokens which are stored into nodes. Uses the list named as 'tokens'. 
  Based on this list makes the frequency of synset into text. Additionally
  chcecks taht the token contains information about disambiguated synset.
  
  @param graph networkx.DiGraph(): a graph
  @return dictionary where key is a pair synset, node identifier and value is 
          frequency of sense in the text.
  """
  senses = dict()
  for n in graph:
    for token in graph.node[n][constants.NODE_TOKENS]:
      md = token.get_metadata()
      if md:
        sense = md.get_attribute(constants.TOKEN_SENSE_UKB_SYNSET_ID)
        if sense:
          sense = int(sense)
          if not senses.has_key(sense):
            senses[(sense, n)] = 0
          senses[(sense, n)] += 1
  return senses


def read_plwn_graph(cfg):
  """!
  
  @param cfg: Config file
  """
  
  logging.info('Loading plWN graph...')
  dbcfg_file  = cfg.plwn_db_config()
  out_pickle = cfg.plwn_pickle()
  plwngraph = PlWNGraph()
  if not plwngraph.read_graph(dbcfg_file, out_pickle):
    logging.error('Cannot connect to database!')
    exit(1)
  return plwngraph