import os
from AppCode.Config import DBConfig
from AppCode.FileHandler import FileHandler
from werkzeug.utils import secure_filename

class DocumentHandler:

    def __init__(self):
        self.years = []
        self.documents = []
        self.isSuccess = False
        self.resultMessage = ""

    # VIEW DOCUMENTS
    def View(self, request):
        year = request.args.get('year', '')
        stage = request.args.get('stage', '')

        dbconfig = DBConfig()
        connection = dbconfig.get_db_connection()

        if not connection:
            self.isSuccess = False
            return

        cursor = connection.cursor(dictionary=True)

        # --- FILTER QUERY ---
        query = "SELECT * FROM documents WHERE 1=1"
        params = []

        if year != "":
            query += " AND year = %s"
            params.append(year)

        if stage != "":
            query += " AND stage = %s"
            params.append(stage)


        cursor.execute(query, params)
        self.documents = cursor.fetchall()

        # ---- GET YEARS FROM STORED PROCEDURE ----
        cursor.callproc("GetYear")

        for result in cursor.stored_results():
            year_rows = result.fetchall()
            break   # only first result set

        self.years = [row['year'] for row in year_rows]

        cursor.close()
        connection.close()
        self.isSuccess = True

    # UPLOAD DOCUMENTS
    def Upload(self, request):
        """Log user actions with timestamp, user, action, and details."""
        
        dbconfig = DBConfig()
        connection = dbconfig.get_db_connection()

        if connection:
            cursor = connection.cursor()
            files = request.files.getlist('documents')
            year = request.form['year']
            stage = request.form['stage']
            
            for file in files:
                if file is not FileHandler.ALLOWED_EXTENSIONS:
                    continue


                filename = secure_filename(file.filename)
                filepath = os.path.join(FileHandler.UPLOAD_FOLDER, filename)
                extension = file.filename.rsplit('.', 1)[1]
                # Need to Check whetehr all three items are required

                file.save(filepath)

                # cursor.execute("""
                #     INSERT INTO documents (filename, filepath, filetype, year, stage)
                #     VALUES (%s, %s, %s, %s, %s)
                # """, (filename, filepath, file.filename.rsplit('.', 1)[1], year, stage))


                cursor.callproc('InsertDocument', [
                    filename,
                    filepath,
                    extension,
                    year,
                    stage
                ])

            connection.commit()
            cursor.close()
            connection.close()
        # return redirect(url_for('view_documents'))
