import sys
import logging
import corpus2
import operator
import grafon.constants as constants
from grafon.graphs.sumograph import SumoGraph

def get_concepts_from_file(tagset, filename):
    """!
    Reads from fileame (with given tagset) the concpets from it.
    
    @param tagset: object of corpus2.Tagset
    @param filename: Filename which will be read.
    @return dictionary of mapping concepts to tokens into text with 
            this concept.
    """
    concepts = dict()
    cclreader = corpus2.CclRelReader(tagset, filename, filename)
    document = cclreader.read()
    for paragraph in document.paragraphs():
        for sentence in paragraph.sentences():
            for token in sentence.tokens():
                md = token.get_metadata()
                concept = None
                if md:
                    concept = md.get_attribute(constants.TOKEN_SUMO_MAP)
                    if concept:
                        for c in concept.split(';'):
                            c = c.split(':')[1]
                            if not concepts.has_key(c):
                                concepts[c] = 0
                            concepts[c] += 1
    return concepts

def get_most_freq_concepts_from_file(tagset, filename, kmfq):
    """!
    For the given filename returns only n most frequent concepts.
    It calls method get_concepts_from_file and select kmfq most frequent.
    
    @param tagset: object of corpus2.Tagset
    @param filename: Filename which will be read.
    @param kmfq: Number of mosft frequent cocnepts to read
    @return dictionary of mapping concepts to tokens into text with 
            this concept.
    """
    concepts = get_concepts_from_file(tagset, filename)
    return dict(sorted(concepts.items(), key=operator.itemgetter(0))[0:kmfq])

def get_concepts_from_nxgraph(graph):
  """!
  From given graph gets all (if exists) sumo concepts.
  Similiar to grafon.utils.plwnproc.get_senses_from_nxgraph but gets concepts.

  From given graph gets all (if exists) concepts from SUMO. This method uses
  the tokens which are stored into nodes. Uses the list named as 'tokens'. 
  Based on this list makes the frequency of concepts 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 concept, node identifier and value is 
          frequency of concept in the text.
  """
  concepts = dict()
  for n in graph:
    for token in graph.node[n][constants.NODE_TOKENS]:
      md = token.get_metadata()
      if md:
        concept = md.get_attribute(constants.TOKEN_SUMO_MAP)
        if concept:
          for c in concept.split(';'):
            c = c.split(':')[1]
            if not c[0].isupper():
              continue
            if not concepts.has_key(c):
              concepts[(c, n)] = 0
            concepts[(c, n)] += 1
  return concepts

def read_sumo_graph(cfg):
  """!
  
  @param cfg: Config file
  """
  logging.info('Loading SUMO graph...')
  sumo_graph_file = cfg.sumo_graph_csv()
  sgraph = SumoGraph()
  sgraph.build_graph(sumo_graph_file)
  return sgraph