import sklearn as sk
import numpy as np
import csv
import sys
import os


def load_data(filename):
    with open(filename, newline='') as csvfile:
        reader = csv.reader(csvfile)
        try:
            data = []
            for row in reader:
                data.append(row)
            print(data)
            return np.array(data)
        except csv.Error as e:
            sys.exit("file {}, line {}".format(filename, row))


def plant_trees(data):
    parameters, classes = data[:], data[:]
    tree = sk.tree.DecisionTreeClassifier()
    tree = tree.fit(parameters, classes)
    return tree


def validation(tree, data):
    confusion_matrix = np.zeros((3, 3))
    parameters = np.array(data)
    classes = data[len(data)-1]
    for parameter, pclass in zip(parameters, classes):
        result = tree.predict(parameter)
        confusion_matrix[result, pclass] += 1
    return confusion_matrix


def report(tree, confusion_matrix):
    print(tree)
    print(confusion_matrix)


def store(tree, confusion_matrix):
    pass


def main():
    filename = sys.argv[1]
    print("Loading file {}".format(filename))
    data = load_data(filename)
    tree = plant_trees(data)
    confusion_matrix = validation(tree)
    report(tree, confusion_matrix)
    store(tree, confusion_matrix)


if __name__ == '__main__':
    main()
