#
# <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 logging
import edgebuiderinterface
import grafon.constants as constants

class WordToWordEdgeBuilder(edgebuiderinterface.EdgeBuiderInterface):
    def __init__(self, str_name = 'w2w'):
      super(WordToWordEdgeBuilder, self).__init__(str_name)

    def add_edges(self, base_graph):
      """!
      The edge is added between two words (tokens) from the text.
      """
      interp_mask = base_graph.tagset.parse_symbol('interp')
      rel_id = 1
      for paragraph in base_graph.document.paragraphs():
        for sentence in paragraph.sentences():
          g = base_graph.graph_dict.get(sentence.id(), None)
          if not g:
            logging.warning('There is no graphs for sentence {}'.format(
            sentence.id()))
            continue
          tokens = []
          # makes filtration of the tokens
          for token in sentence.tokens():
            if base_graph.skip_token(token):
                continue
            tag = token.get_preferred_lexeme(base_graph.tagset).tag()
            if tag.get_masked(interp_mask) != interp_mask:
              tokens.append(token)
          for i, token in enumerate(tokens):
            if i + 1 == len(tokens):
              break
            from_nodes = base_graph.node_converter.key(tokens[i])
            to_nodes = base_graph.node_converter.key(tokens[i + 1])
            for fn in from_nodes:
              if not g.has_node(fn):
                continue
              for tn in to_nodes:
                if not g.has_node(tn):
                  continue
                if fn and tn:
                  if self.exists_edge(g, fn, tn, self._str_name):
                    g[fn][tn][self._str_name][constants.EDGE_COUNT] += 1
                  else:
                    g.add_edge(
                      fn, tn, key=self._str_name, attr_dict={
                        constants.EDGE_LABEL: self._str_name,
                        constants.EDGE_RELID: rel_id,
                        constants.EDGE_COUNT: 1})
              rel_id += 1