from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, jsonify, send_from_directory, session

import utils
from app.ui.views_base import BaseView
from app.services.service_log import LogService
from app.services.log_helper import OperationType,OperationModule

LogService = LogService()

log_bp = Blueprint('log', __name__, template_folder='templates')

@log_bp.route('/log_list')
@BaseView.login_required
def log_list():
    page = request.args.get('p', 1, type=int)
    per_page = request.args.get('pp', 10, type=int)
    username = request.args.get('u', '')
    operation_type = request.args.get('ot', '')
    operation_module = request.args.get('om', '')
    start_date = request.args.get('s', '')
    end_date = request.args.get('e', '')

    try:
        start_date_obj = datetime.strptime(start_date, '%Y-%m-%d') if start_date else None
        end_date_obj = datetime.strptime(end_date + ' 23:59:59', '%Y-%m-%d %H:%M:%S') if end_date else None

        logs, total_count = LogService.get_logs_paginated(
            page=page,
            per_page=per_page,
            username=username if username else None,
            operation_type=operation_type if operation_type else None,
            operation_module=operation_module if operation_module else None,
            start_date=start_date_obj,
            end_date=end_date_obj
        )

        return render_template('log/list.html',
                             log_list=logs,
                             username=username,
                             start_date=start_date,
                             end_date=end_date,
                             page=page,
                             per_page=per_page,
                             total_count=total_count,
                             operation_type=operation_type,
                             operation_module=operation_module,
                             operation_module_list=[op.value for op in OperationModule],
                             operation_type_list=[op.value for op in OperationType])
    except Exception as e:
        utils.get_logger().error(f"Error in log_list: {str(e)}")
        return render_template('log/list.html',
                             log_list=[],
                             username=username,
                             start_date=start_date,
                             end_date=end_date,
                             page=1,
                             per_page=per_page,
                             total_count=0,
                             operation_type=operation_type,
                             operation_module=operation_module,
                             operation_module_list=[op.value for op in OperationModule],
                             operation_type_list=[op.value for op in OperationType])
