from flow_elem import FlowElem
import os, codecs, csv
from collections import defaultdict

class Sumo(FlowElem):
  """
  It is wrapper for sumo ccl processor placed in plumper project. It processes
  corpus2.Document objects and adds to them relaetions and annotations.
  """
  def __init__(self, config):
    """
    @type config: saper.config.ConfigLoader
    """
    #! File with mapping
    self._plwn2sumo_automap_file = config.get('sumo', 'plwn2sumo_automap_file')
    
    #! A dictionary where the mapping result will be stored
    self._plwn_sumo_dict = None

  def feed_flow(self, document):
    """
    Method feeds the sumo processor and returns the annotated and
    relation enriched corpus2.Document.

    @type document: corpus2.Document
    @rtype: corpus2.Document
    """
    return self._process_document(document)

  def _process_document(self, document):
    if not self._plwn_sumo_dict:
      self._plwn_sumo_dict = self._get_plwn_sumo_dict()

    for paragraph in document.paragraphs():
      for sentence in paragraph.sentences():
        for token in sentence.tokens():
          md = token.get_metadata()
          if md:
            ukb_syn_id = md.get_attribute('sense:ukb:syns_id')
            if ukb_syn_id and ukb_syn_id in self._plwn_sumo_dict:
              md.set_attribute('sumo_map', \
                ';'.join([sumo_str for sumo_str 
                          in self._plwn_sumo_dict[ukb_syn_id]]))
    return document

  def _get_plwn_sumo_dict(self):
    plwn_sumo_dict = defaultdict(set)

    if not os.path.exists(self._plwn2sumo_automap_file):
      raise IOError("{0} file not found!".format(self._plwn2sumo_automap_file))

    with codecs.open(self._plwn2sumo_automap_file, 'rt') as csvfile:
      csvreader = csv.reader(csvfile, delimiter=';', quotechar='"')
      for line in csvreader:
        plWN_id = line[0]
        sumo_str = line[8]
        map_rel = line[9]
        plwn_sumo_dict[plWN_id].add(("%s:%s") % (map_rel, sumo_str))
    return plwn_sumo_dict