from flask import Flask, render_template, request, redirect, url_for, send_from_directory, flash, jsonify, json
from flask import current_app

from datetime import datetime
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user

from model.Utilities import RegEx, ResponseHandler, HtmlHelper, ItemCRUDType
from model.Log import LogData, LogHelper

import os
import config
import re

import mysql.connector
from mysql.connector import Error

class State:

    isSuccess = False
    resultMessage = ""

    def __init__(self):
        self.isSuccess = False
        self.resultMessage = ""

    def AddState(self, request):
        """Log user actions with timestamp, user, action, and details."""
        statedata = []
        
        connection = config.get_db_connection()

        if connection:
            cursor = connection.cursor()
            state_name = request.form['state_Name'].strip()
            LogHelper.log_action("Add State", f"User {current_user.id} added state '{state_name}'")

            if not re.match(RegEx.patternAlphabetOnly, state_name):
                self.isSuccess = False
                self.resultMessage = HtmlHelper.json_response(ResponseHandler.invalid_name("state"), 400)
                return

            try:

                cursor.callproc("CheckStateExists", (state_name,))
                for data in cursor.stored_results():
                    existing_state = data.fetchone()

                if existing_state:
                    self.isSuccess = False
                    self.resultMessage = HtmlHelper.json_response(ResponseHandler.already_exists("state"), 409)
                    return

                # cursor.execute("call SaveState (%s)", (state_name,))
                cursor.callproc("SaveState", (state_name,))
                connection.commit()
                self.isSuccess = True
                self.resultMessage = HtmlHelper.json_response(ResponseHandler.add_success("state"), 200)
                return

            except mysql.connector.Error as e:
                print(f"Error inserting state: {e}")
                self.isSuccess = False
                self.resultMessage = HtmlHelper.json_response(ResponseHandler.add_failure("state"), 500)
                return

            #Need to make this seperate



    def GetAllStates(self, request):
        """Log user actions with timestamp, user, action, and details."""
        statedata = []
        connection = config.get_db_connection()
    
        self.isSuccess = False
        self.resultMessage = ""

        if not connection:
            return []
        
        cursor = connection.cursor()

        try:
            cursor.callproc("GetAllStates")
            for res in cursor.stored_results():
                statedata = res.fetchall()
            self.isSuccess = True

        
        except mysql.connector.Error as e:
            print(f"Error fetching states: {e}")
            self.isSuccess = False
            self.resultMessage = HtmlHelper.json_response(ResponseHandler.fetch_failure("state"), 500)
            return []    

        finally:
            cursor.close()
            connection.close()

        return statedata



    def CheckState(self, request):
        self.isSuccess = False
        self.resultMessage = ""

        connection = config.get_db_connection()
        #connection closing needs to be verified
        if connection:
            cursor = connection.cursor()
            state_name = request.json.get('state_Name', '').strip()
            LogHelper.log_action("Check State", f"User {current_user.id} Checked state '{state_name}'")
            if not re.match(RegEx.patternAlphabetOnly, state_name):
                self.isSuccess = False
                self.resultMessage = HtmlHelper.json_response(ResponseHandler.invalid_name("state"), 400)
                return HtmlHelper.json_response(ResponseHandler.invalid_name("state"), 400)

            try:
                # cursor.execute("SELECT * FROM states WHERE State_Name = %s", (state_name,))
                # existing_state = cursor.fetchone()

                cursor.callproc("CheckStateExists", (state_name,))
                for data in cursor.stored_results():
                    existing_state = data.fetchone()

                if existing_state:
                    self.isSuccess = False
                    self.resultMessage = HtmlHelper.json_response(ResponseHandler.already_exists("state"), 409)
                    return HtmlHelper.json_response(ResponseHandler.already_exists("state"), 409)
                else:
                    self.isSuccess = True
                    self.resultMessage = HtmlHelper.json_response(ResponseHandler.is_available("state"), 200)
                    return HtmlHelper.json_response(ResponseHandler.is_available("state"), 200)

            except mysql.connector.Error as e:
                self.isSuccess = False
                self.resultMessage = HtmlHelper.json_response(ResponseHandler.add_failure("state"), 500)

                print(f"Error checking state: {e}")
                return HtmlHelper.json_response(ResponseHandler.add_failure("state"), 500)
            finally:
                cursor.close()
                connection.close()



    def DeleteState(self, request, id):
        self.isSuccess = False
        self.resultMessage = ""

        connection = config.get_db_connection()
        cursor = connection.cursor()
        LogHelper.log_action("Delete State", f"User {current_user.id} Deleted state '{id}'")
        try:
            cursor.callproc('DeleteState', (id,))
            connection.commit()

            self.resultMessage = "Successfully Deleted"
            self.isSuccess = True
        except mysql.connector.Error as e:
            print(f"Error deleting data: {e}")
            self.isSuccess = False
            self.resultMessage = HtmlHelper.json_response(ResponseHandler.delete_failure("state"), 500)
            return HtmlHelper.json_response(ResponseHandler.delete_failure("state"), 500)

        finally:
            cursor.close()
            connection.close()
        return self.resultMessage
    

    def EditState(self, request, id):
        self.isSuccess = False
        self.resultMessage = ""

        connection = config.get_db_connection()
        cursor = connection.cursor()
        # str_pattern_reg = r"^[A-Za-z\s]+$"

        state_name = request.form['state_Name'].strip()
        LogHelper.log_action("Edit State", f"User {current_user.id} Edited state '{state_name}'")
        if not re.match(RegEx.patternAlphabetOnly, state_name):
            self.isSuccess = False
            self.resultMessage = ResponseHandler.invalid_name("state"), 400
            return ResponseHandler.invalid_name("state"), 400

        try:
            # cursor.execute("UPDATE states SET State_Name = %s WHERE State_ID = %s", (state_name, id))
            cursor.callproc("UpdateStateById", (id, state_name))
            connection.commit()
            self.isSuccess = True
            self.resultMessage = "Successfully Edited"
            return redirect(url_for('state.add_state'))
        except mysql.connector.Error as e:
            print(f"Error updating data: {e}")
            self.isSuccess = True
            self.resultMessage = ResponseHandler.add_failure("state"), 500

            return ResponseHandler.add_failure("state"), 500
        finally:
            cursor.close()
            connection.close()





    def GetStateByID(self, request, id):
        """Log user actions with timestamp, user, action, and details."""
        statedata = []
    
        self.isSuccess = False
        self.resultMessage = ""

        connection = config.get_db_connection()
        if not connection:
            return []        
        cursor = connection.cursor()

        try:
            cursor.callproc("GetStateByID", (id,))
            for res in cursor.stored_results():
                statedata = res.fetchone()

            if statedata:
                self.isSuccess = True
                self.resultMessage = "Success in Fetching"
            else:
                self.isSuccess = False
                self.resultMessage = "State Not Found"

        
        except mysql.connector.Error as e:
            print(f"Error fetching states: {e}")
            self.isSuccess = False
            self.resultMessage = HtmlHelper.json_response(ResponseHandler.fetch_failure("state"), 500)
            return []    

        finally:
            cursor.close()
            connection.close()

        return statedata


