import os
from ltlearn.classification.makers.maker import Maker
import ConfigParser
from ConfigParser import SafeConfigParser
from fextor import Fextor
from chunkrel.core import get_matrix
from chunkrel.core import save_relations
from chunkrel.core import get_config_defaults
from copy import copy


S_OPTIONS = 'options'
O_MODELDIR = 'datadir'
O_LEXCSDCONF = 'lexcsd-config'
O_FEXTORCONF = 'fextor-config'
O_TAGSET = 'tagset'
class Plugin():

        def __init__(self,config):
                self.config = None
                with open(config) as config_file:
                        self.config = ConfigParser.RawConfigParser()
                        self.config.readfp(config_file)
                self.workdir = self.config.get(S_OPTIONS, O_MODELDIR)
                self.lexcsd_config = self.config.get(S_OPTIONS, O_LEXCSDCONF)
                self.fextor_config = self.config.get(S_OPTIONS, O_FEXTORCONF)
                self.tagset =  self.config.get(S_OPTIONS, O_TAGSET)
                self.relation = self.read_relation_kinds()
                classifiers = self.get_lexcsd_classifiers()
                self.the_classifier = classifiers[0]
                self.error_flag = 0 # if input has no enumerated sentences then count it as error and try again, if something goes wrong again than break and return processing



        def process(self, inputFile, outputFile):
                open(inputFile+".tmp","a+")
                fextractor = Fextor([inputFile], self.fextor_config, inputFile+".tmp", False, False, self.tagset, 'document', None)
                attrs = Attributes()
                attrs.datadir = self.workdir
                attrs.verbose = False
                train_matrix_possible_classes = copy(self.the_classifier._train_matrix.possible_classes)
                for document in fextractor.iterate_documents():
                        try:
                                (pointers, matrix_path) = get_matrix(document, fextractor, self.fextor_config, inputFile+".tmp", self.workdir, attrs)
                        except KeyError as ke:
                                if self.error_flag == 0 :
                                        print("Input has no enumerated sentences. Calling self.autogen_sent_id(request) and trying again")
                                        self.error_flag = 1
                                        self.autogen_sent_id(request)
                                        self.process(request)
                                        self.error_flag = 0
                                        return 0
                                else:
                                        self.l.warn("Malformed request.")
                                        self.error_flag = 0
                                        raise Exception("Bad request")
                        if matrix_path:
                                relation_flags = self.the_classifier.classify(matrix_path)
                                self.the_classifier._train_matrix.possible_classes = copy(train_matrix_possible_classes)
                                attrs = Attributes()
                                attrs.relation = self.relation
                                save_relations(document, pointers, relation_flags, outputFile, attrs)
                        else:
                                print("get_matrix(document, fextractor, self.fextor_config, csv_file, temp_dir, attrs) returned no matrix_path!")
                os.remove(inputFile+".tmp")
                os.remove(inputFile+".tmp.csv")
		os.remove(inputFile+".tmp.tar.bz2")
                return 0

        def read_relation_kinds(self):
                fextor_cfg = SafeConfigParser(None)
                relation = None
                with open(self.fextor_config) as cfg_file:
                        fextor_cfg.readfp(cfg_file)

                for sect in fextor_cfg.sections():
                        if fextor_cfg.has_option(sect, 'relations'):
                                assert relation == None, "Too many 'relations' option defined in .ini file. Only one allowed"
                                return fextor_cfg.get(sect, 'relations').split()

        def get_lexcsd_classifiers(self):
                attrs = Attributes()
                attrs.datadir = self.workdir
                defaults = get_config_defaults(attrs)
                maker = Maker()
                return maker.make_classifiers_from_config(self.lexcsd_config, defaults)


class Attributes:
        pass

