"""
This class handles the output of MSR function. It reads and checks
if between given two worss edge should be added

"""
import sys
import logging

class MSRHandl(object):
  def __init__(self, msr_file_path):
    self.msr_dict = {}
    logging.info('Reading MSR file {}'.format(msr_file_path))
    self._read_msr_file(msr_file_path)
    logging.info('MSR file loaded!')

  def _read_msr_file(self, msr_file_path):
    with open(msr_file_path, 'rt') as fin:
      key = None
      for line in fin:
        spline = line.split('\t')

        if len(spline) > 1:
          if not key:
            logging.error('Error while reading MSR file - no base key found!')
            logging.error('Please check your MSR file if is correct!')
            return
          # print >> sys.stderr, line.strip()
          sword = spline[1].split(';')[0].split(':')[1].strip().decode('utf8')
          self.msr_dict[key].append(sword)
        else:
          if len(spline) == 0:
            continue
          key = spline[0].split(':')[1].strip().decode('utf8')
          if not self.msr_dict.has_key(key):
            self.msr_dict[key] = []

  def can_add_edge(self, w1, w2):
    """
    Funkcja sprawdza czy pomiedzy danymi slowami powinno sie dodac nowa krawedz

    Jezeli w slowniku jest klucz w1 lub w2 i posiada on w liscie kbestow 
    odpowiedni w2 lub w1 wtedy krawedz powinna byc dodana, w przeciwnym razie
    krawedz nie powinna byc dodawana i zwracane jest False.
    """
    w1 = w1.lower().decode('utf8')
    w2 = w2.lower().decode('utf8')
    if self.msr_dict.has_key(w1):
      if w2 in self.msr_dict[w1]:
        return True
    if self.msr_dict.has_key(w2):
      if w1 in self.msr_dict[w2]:
        return True
    return False
