import frappe
from custom_ui.services import DbService, AddressService, ClientService

def before_insert(doc, method):
    print("DEBUG: Before Insert Triggered for On-Site Meeting")
    if doc.project_template == "SNW Install":
        address_doc = AddressService.get_or_throw(doc.address)
        # Address.onsite_meetings is a child table with two fields: onsite_meeting (Link) and project_template (Link). Iterate through to see if there is already an SNW Install meeting linked.
        for link in address_doc.onsite_meetings:
            if link.project_template == "SNW Install":
                if frappe.db.get_value("On-Site Meeting", link.onsite_meeting, "status") != "Cancelled":
                    raise frappe.ValidationError("An On-Site Meeting with project template 'SNW Install' is already linked to this address.")

def after_insert(doc, method):
    print("DEBUG: After Insert Triggered for On-Site Meeting")
    print("DEBUG: Linking bid meeting to customer and address")
    AddressService.append_link_v2(doc.address, "onsite_meetings", {"onsite_meeting": doc.name, "project_template": doc.project_template})
    AddressService.append_link_v2(doc.address, "links", {"link_doctype": "On-Site Meeting", "link_name": doc.name})
    ClientService.append_link(doc.party_name, "onsite_meetings", "onsite_meeting", doc.name)
    if doc.project_template == "SNW Install":
        print("DEBUG: Project template is SNW Install, updating Address status to In Progress")
        AddressService.update_value(doc.address, "onsite_meeting_scheduled", "In Progress")
        
        
def before_save(doc, method):
    
    print("DEBUG: Before Save Triggered for On-Site Meeting")
    if doc.status != "Scheduled" and doc.start_time and doc.end_time and doc.status != "Completed" and doc.status != "Cancelled":
        print("DEBUG: Meeting has start and end time, setting status to Scheduled")
        doc.status = "Scheduled"
    if doc.project_template == "SNW Install":
        print("DEBUG: Project template is SNW Install")
        if doc.status == "Completed":
            print("DEBUG: Meeting marked as Completed, updating Address status")
            AddressService.update_value(doc.address, "onsite_meeting_scheduled", "Completed")
        if doc.status == "Cancelled":
            print("DEBUG: Meeting marked as Cancelled, updating Address status")
            AddressService.update_value(doc.address, "onsite_meeting_scheduled", "Not Started")
                
def validate_address_link(doc, method):
    print("DEBUG: Validating Address link for On-Site Meeting")
    if doc.onsite_meeting:
        meeting = DbService.get_or_throw("On-Site Meeting", doc.onsite_meeting)
        doc.project_template = meeting.project_template