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

import os

class LogHelper:
    @staticmethod
    def log_action(action, details=""):
        """Log user actions with timestamp, user, action, and details."""
        logData = LogData()
        logData.WriteLog(action, details="")

class LogData:

    filepath = ""
    timestamp = None

    def __init__(self):
        self.filepath = os.path.join(current_app.root_path, 'activity.log')
        self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        if hasattr(current_user, "cn") and current_user.cn:
            self.user = current_user.cn
        elif hasattr(current_user, "username") and current_user.username:
            self.user = current_user.username
        elif hasattr(current_user, "sAMAccountName") and current_user.sAMAccountName:
            self.user = current_user.sAMAccountName
        else:
            self.user = "Unknown"

    def WriteLog(self, action, details=""):
        """Log user actions with timestamp, user, action, and details."""
        
        with open(self.filepath, "a", encoding="utf-8") as f:
            f.write(
                f"Timestamp: {self.timestamp} | "
                f"User: {self.user} | "
                f"Action: {action} | "
                f"Details: {details}\n"
            )


    def GetActivitiesLog(self):
        logs = []

        if os.path.exists(self.filepath):
            with open(self.filepath, 'r') as f:
                for line in f:
                    parts = line.strip().split(" | ")
                    if len(parts) == 4:
                        logs.append({
                            "timestamp": parts[0].replace("Timestamp:", "").strip(),
                            "user": parts[1].replace("User:", "").strip(),
                            "action": parts[2].replace("Action:", "").strip(),
                            "details": parts[3].replace("Details:", "").strip()
                        })
        return logs

    def GetFilteredActivitiesLog(self, startDate, endDate, userName):

        filtered_logs = self.GetActivitiesLog()

        # Date filter
        if startDate or endDate:
            try:
                start_dt = datetime.strptime(startDate, "%Y-%m-%d") if startDate else datetime.min
                end_dt = datetime.strptime(endDate, "%Y-%m-%d") if endDate else datetime.max


                filtered_logs = [
                    log for log in filtered_logs
                    if start_dt <= datetime.strptime(log["timestamp"], "%Y-%m-%d %H:%M:%S") <= end_dt
                ]


            except Exception as e:
                print("Date filter error:", e)
            #Why catching all exceptions? Need to handle specific exceptions

        # Username filter
        if userName:
            filtered_logs = [log for log in filtered_logs if userName.lower() in log["user"].lower()]

        return filtered_logs