import frappe

from custom_ui.services import TaskService

def on_update(doc, method):
    print("DEBUG: On Update Triggered for Service Appointment")
    # event = TaskService.determine_event(doc)
    # if event:
        # tasks = TaskService.get_tasks_by_project(doc.project)
        # task_names = [task.name for task in tasks]
        # TaskService.calculate_and_set_due_dates(task_names=task_names, event=event, triggering_doctype="Service Address 2")

def after_insert(doc, method):
    print("DEBUG: After Insert Triggered for Service Appointment")
    task_names = [task.name for task in TaskService.get_tasks_by_project(doc.project)]
    TaskService.fire_task_triggers(task_names=task_names, event="Created", current_triggering_dict=doc.as_dict())

def before_save(doc, method):
    print("DEBUG: Before Save Triggered for Service Appointment")
    if doc.status == "Open" and doc.expected_start_date:
        doc.status = "Scheduled"
    elif doc.status == "Scheduled" and not doc.expected_start_date:
        doc.status = "Open"
    if doc.status == "Scheduled" and doc.actual_start_date:
        doc.status = "Started"
    elif doc.status != "Completed" and doc.status != "Canceled" and doc.actual_end_date:
        doc.status = "Completed"
    event = TaskService.determine_event(doc)
    if event:
        task_names = [task.name for task in TaskService.get_tasks_by_project(doc.project)]
        TaskService.fire_task_triggers(task_names=task_names, event=event, current_triggering_dict=doc.as_dict())
    if doc.status == "Completed" and frappe.get_value("Service Address 2", doc.name, "status") != "Completed":
        frappe.set_value("Project", doc.project, "invoice_status", "Ready to Invoice")