#
# <one line to give the library's name and an idea of what it does.>
# Copyright (C) 2014    <copyright holder> <email>
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.    See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.    If not, see <http://www.gnu.org/licenses/>.
# 
#

import doublereledgebuilder
import needgebuilderinterface
from collections import defaultdict

class NESemRelEdgeBuilder(doublereledgebuilder.DoubleRelEdgeBuilder, 
                          needgebuilderinterface.NEEdgeBuilderInterface):
  """!
  The class creates edges between named entities' (NE) nodes from the text 
  that belongs to the set 'Semantic relations'. Connections between tokens are
  written in the rel-ccl file. 
  Semantic relations in a text are recognized by the tool SEREL.
  """
  def __init__(self, str_name = 'NE_sem_rel', set_name = 'Semantic relations'):
    """!
    Create the class by calling the constructor of it's parent.

    @param str_name the name assigned to edges that are created by this class.
    @type str_name: str
    """
    super(NESemRelEdgeBuilder, self).__init__(str_name, set_name = set_name)

  def _get_rels_dir(self, relations):
    """!
    Return the list of relations for each sentence and the set of channels.

    This method overwrites the parent's implementation. It extracts semantic 
    relations for each sentence and add it to a dictionary where keys are  
    sentence's identifiers and values are the lists of relations. Moreover,
    it stores the channels' names that belong to the set 'Semantic relations'.

    @param relations the list of relations in the document
    @type relations: iterable object

    @return the dictionary of relations for each sentence and the set of 
      channels that belong to semantic realations.
    @rtype: tuple
    """
    drels = defaultdict(list)
    accepted_channels = set()
    for r in relations:
      pfrom = r.rel_from()
      if pfrom.channel_name() == self._chan_name:
        drels[pfrom.sentence_id()].append(r)
        accepted_channels.add(self._chan_name)
      elif r.rel_set() == self._set_name \
        and self.get_ne_set_name(pfrom.channel_name()):
        drels[pfrom.sentence_id()].append(r)
        accepted_channels.add(pfrom.channel_name())
    return drels, accepted_channels

