import frappe
import datetime
from custom_ui.db_utils import process_query_conditions, build_datatable_dict, get_count_or_filters, build_success_response, build_error_response
from custom_ui.services import DbService

@frappe.whitelist()
def set_task_status(task_name, new_status):
    """Set the status of a specific task."""
    try:
        task = DbService.get_or_throw("Task", task_name)
        task.status = new_status
        task.save()
        return build_success_response(f"Task {task_name} status updated to {new_status}.")
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def get_job_task_list(job_id=""):
    if job_id:
        try:
            tasks = frappe.get_all('Task', filters={"project": job_id})
            task_docs = {task_id: frappe.get_doc(task_id) for task_id in tasks}
            return build_success_response(task_docs)
        except Exception as e:
            return build_error_response(str(e), 500)


@frappe.whitelist()
def get_task_status_options():
    print("DEBUG: Getting task status options")
    try:
        task_doctype = frappe.get_doc("DocType", "Task")
        status_index = 0
        for i, field in enumerate(task_doctype.fields):
            if field.fieldname == "status":
                status_index = i
                break
        options = task_doctype.fields[status_index].options.split()
        print("DEBUG: Task Status options retreived", options)
        return build_success_response(options)
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def get_tasks_due(subject_filter, current_company):
    """Return the number of items due today of the type of subject_filter"""
    try:
        today = datetime.date.today()
        due_filters = {
            'subject': ['like', f'%{subject_filter}%'],
            'status': ['not in', ["Template", "Completed", "Cancelled"]],
            'company': current_company,
            'exp_end_date': today,
            # Add due date filter here
        }
        completed_filters = {
            'subject': ['like', f'%{subject_filter}%'],
            'status': ['not in', ["Template", "Cancelled"]],
            'company': current_company,
            'exp_end_date': today,
            # Add due date filter here
        }
        overdue_filters = {
            'subject': ['like', f'%{subject_filter}%'],
            'status': ['not in', ["Template", "Completed", "Cancelled"]],
            'company': current_company,
            'exp_end_date': ["<", today]
            # Add overdue date filtering here
        }
        due_count = frappe.db.count("Task", filters=due_filters)
        completed_count = frappe.db.count("Task", filters=completed_filters)
        overdue_count = frappe.db.count("Task", filters=overdue_filters)
        return build_success_response([due_count, completed_count, overdue_count])
    except frappe.ValidationError as ve:
        return build_error_response(str(ve), 400)
    except Exception as e:
        return build_error_response(str(e), 500)


@frappe.whitelist()
def get_tasks_table_data(filters={}, sortings=[], page=1, page_size=10):
    """Get paginated task table data with filtering and sorting support."""
    try:
        print("DEBUG: Raw task options received:", filters, sortings, page, page_size)

        processed_filters, processed_sortings, is_or, page, page_size = process_query_conditions(filters, sortings, page, page_size)

        processed_filters['status'] = ["not in", ["Template", "Completed", "Cancelled"]]

        print("Processed filters:", processed_filters)

        count = frappe.db.count("Task", filters=processed_filters)

        tasks = frappe.db.get_all(
            "Task",
            fields=["*"],
            filters=processed_filters,
            limit=page_size,
            start=(page-1) * page_size,
            order_by=processed_sortings
        )

        print("TASKS?", tasks, page, page_size)

        tableRows = []
        for task in tasks:
            tableRow = {}
            tableRow["id"] = task["name"]
            tableRow["subject"] = task["subject"]
            tableRow["project"] = task["project"]
            tableRow["address"] = task.get("custom_property", "")
            tableRow["status"] = task.get("status", "")
            tableRows.append(tableRow)

        data_table_dict = build_datatable_dict(data=tableRows, count=count, page=page, page_size=page_size)
        return build_success_response(data_table_dict)
    except frappe.ValidationError as ve:
        return build_error_response(str(ve), 400)
    except Exception as e:
        return build_error_response(str(e), 500)
