from main_imports import MDScreen
from ProjectFiles.applibs import utils
import warnings
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
from six import StringIO
import pydotplus
from sklearn.tree import DecisionTreeClassifier

warnings.filterwarnings('ignore')
utils.load_kv("Paddy_Waste.kv")


class Paddy_Waste_Screen(MDScreen):

    def selectbtn1(self):
        self.l3.text = "KeeriSamba"

        pass

    def selectbtn2(self):
        self.l3.text = "Nadu"
        pass

    def selectbtn3(self):
        #  organic = 1
        self.l2.text = "1"

    def btnA(self):
        SeedType = self.l3.text
        dataset = pd.read_csv('FarmingData/DataCollected.csv')
        dataset.shape

        dataset['chemicalsType'].replace({'organic': 1}, inplace=True)
        dataset = dataset[(dataset["SeedType"] == SeedType)]

        dataset['WasteAmount'] = (dataset['wastage'] / 100) * dataset['production']

        tableData = dataset.head()
        print(tableData)

        # Preparing the Data
        feature_cols = ['Seeds', 'DailyWater', 'chemicalsType']

        X = dataset[['Seeds', 'DailyWater', 'chemicalsType']]
        y = dataset['WasteAmount']

        # Training and Making Predictions
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)

        # set  DecisionTreeClassifier algorithm
        classifier = DecisionTreeClassifier()
        classifier.fit(X_train, y_train)
        y_pred = classifier.predict(X_test)

        dot_data = StringIO()
        export_graphviz(classifier, out_file=dot_data,
                        filled=True, rounded=True,
                        special_characters=True, feature_names=feature_cols, class_names=['0', '1'])
        graph = pydotplus.graph_from_dot_data(dot_data.getvalue())

        # used Seeds Kg , DailyWater , chemicalsType Used

        Seeds = self.txt3.text
        DailyWater = self.txt4.text
        chemicalsType  = self.l2.text

        new_input = [[Seeds, DailyWater, chemicalsType]]
        pred = classifier.predict(new_input)
        print(pred)

        self.l1.text = str(pred[0])

    pass
