import csv
from CertainTrust import Opinion


class CSVReader:
    @staticmethod
    def readCSV(inputfile, f, months):
        '''
        Converts input csv file into a dictionary of opinions,
        The CSV input file should contain the following structure:
        packageName:prediction:errorComplement
        :param inputfile: relative path to input csv file
        :param f: initial expectation value
        :param months: number of months
        :return: dictionary of package-names as key and opinions as value
        '''
        result = {}
        with open(inputfile, newline="") as csvfile:
            reader = csv.reader(csvfile, delimiter=':', quotechar='|')
            for row in reader:
                if not len(row) == 0:
                    package = row [0]
                    prediction = row [1]
                    errorCompl = float(row [2])
                    # FIXME: HARDCODED MONTHS
                    resT = 1 - int(prediction) / (30 * months)
                    result[package]=Opinion(resT , errorCompl, f)
        return result

    @staticmethod
    def readCSVModel(months):
        '''
        Reads a model from CSV file into python dictionary
        :param months: number of months
        :return: dictionary of package-names as key and opinions as value
        '''
        result = {}
        with open("models/dummy_model_"+str(months)+".csv", newline="") as csvfile:
            reader = csv.reader(csvfile, delimiter=':', quotechar='|')
            for row in reader:
                if not len(row) == 0:
                    result[row[0]]=Opinion(float(row[1]),float(row[2]),float(row[3]))
        return result

    @staticmethod
    def readCSVPackages(filename):
        '''
        reads package names from csv file
        :param filename:
        :return: dictionary of package names
        '''
        result = []
        with open(filename, newline="") as csvfile:
            reader = csv.reader(csvfile, delimiter=':', quotechar='|')
            for row in reader:
                if not len(row) == 0:
                    result.append(row[0])
        return result


'''
res =CSVReader.readCSV("inputs/dummy_input.csv", 1)
for key in res:
    print(key + ":" + str(res[key].t)+ ":" + str(res[key].c)+ ":" + str(res[key].f))

CSVReader.readCSVPackages("inputs/dummy_input_package.csv")
'''