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

class HeadToHeadEdgeBuilder(edgebuiderinterface.EdgeBuiderInterface):
  def __init__(self, str_name = 'h2h', chan_name = 'chunk_agp'):
    super(HeadToHeadEdgeBuilder, self).__init__(str_name, chan_name)

  def add_edges(self, base_graph):
    """!
    The edge is added for the nodes represents agp-heads 
    in the order like in the text

    @param base_graph: Object of grafon.graphs.BaseGraph
    """
    for paragraph in base_graph.document.paragraphs():
      for sentence in paragraph.sentences():
        tokens = []
        g = base_graph.graph_dict.get(sentence.id(), None)
        if not g:
          logging.warning('There is no graphs for sentence {}'.format(
            sentence.id()))
          continue
        asent = corpus2.AnnotatedSentence.wrap_sentence(sentence)
        channel = asent.get_channel(self._chan_name)
        for i, seg in enumerate([s for s in channel.segments()]):
          if seg != 0 and channel.is_head_at(i):
            token = asent.tokens()[i]
            if base_graph.skip_token(token):
              continue
            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_COUNT: 1})
