from flow_elem import FlowElem
from saper.saperio import utils
from saper.utils import chunkrelproc
import corpus2


class Chunkrel(FlowElem):
    """
    """

    def __init__(self, config):
        self.config_path = config.get('chunkrel', 'config')
        self.tagset = corpus2.get_named_tagset(config.get('saper', 'tagset'))

    def feed_flow(self, document):
        """
        It preforms chunkrel process on given document and returns annotated
        document.

        @type document: corpus2.Document
        @rtype: corpus2.Document
        """

        #Creating tempfile.
        temp = utils.get_temp_file(document, self.tagset)

        #Running chunkrel.
        chrel = chunkrelproc.Plugin(self.config_path)
        chrel.process(temp.name,temp.name)

        rel_reader = corpus2.RelationReader(temp.name)
        relations = rel_reader.relations()
        for rel in relations:
            document.add_relation(rel)
        temp.close()

        return document

