import macaproc, yielders

__author__ = 'blaz'
import corpus2
from wcrft.tagger import Tagger as WcrftTagger


class Tagger(object):
    def __init__(self):
        """
        Init Tagger processor with configuration from config_path

        @param config_path: filepath for Tagger's configuration
        """
        self.ambiguity = False
        self.tagger = WcrftTagger("nkjp_s2.ini", "model_nkjp10_wcrft_s2", False)
        self.tagger.load_model()

    def tagging_document(self, document, preserve_chunks=False,
                         premorph=False, path=''):
        """Tagging document

        @param document: text document (string or file path in premorph mode)
        @param preserve_chunks: document structure (default False)
        @param premoph: premorph mode if True
        """
        tagged_document = corpus2.Document(path=path)
        if premorph:
            maca_text_reader = \
                macaproc.get_maca_file_premorph_reader(document,
                                                       self.tagger.maca_config)
        else:
            maca_text_reader = \
                macaproc.get_maca_string_reader(document,
                                                self.tagger.maca_config)

        if preserve_chunks:
            for chunk in yielders.chunks(maca_text_reader):
                tagged_chunk = corpus2.Chunk().clone_shared()
                tagged_chunk.set_attribute('id', chunk.get_attribute('id'))
                for sentence in self._tagged_sentences(chunk):
                    tagged_chunk.append(sentence)
                tagged_document.add_paragraph(tagged_chunk)
        else:
            tagged_chunk = corpus2.Chunk().clone_shared()
            for chunk in yielders.chunks(maca_text_reader):
                for sentence in self._tagged_sentences(chunk):
                    tagged_chunk.append(sentence)
            tagged_document.add_paragraph(tagged_chunk)
        tagset = maca_text_reader.tagset()
        del maca_text_reader
        return tagged_document, tagset

    def _tagged_sentences(self, chunk):
        """Yields tagged sentence

        @param chunk: corpus2.Chunk
        """
        for sentence in chunk.sentences():
            sentence_ptr = corpus2.AnnotatedSentence.wrap_sentence(
                sentence).clone_shared()
            self.tagger.tag_sentence(sentence_ptr, self.ambiguity)
            yield sentence_ptr
