from playwright.sync_api import sync_playwright
import os

# ── CONFIG ──────────────────────────────────────────────────────────────────
BASE_URL = "https://janssen.4gclinical.com"

EMAIL    = "vbuzalka@its.jnj.com"
PASSWORD = "Vlado123++-+"

# STUDY = "42847922MDD3003"
STUDY = "77242113UCO3001"

OUTPUT_DIR = f"xls_ip_destruction_{STUDY}"
# ────────────────────────────────────────────────────────────────────────────

def run(page, study):
    output_dir = f"xls_ip_destruction_{study}"
    os.makedirs(output_dir, exist_ok=True)

    page.goto(f"{BASE_URL}/report/ip_destruction_form")
    page.wait_for_load_state("networkidle", timeout=120000)

    page.locator('input[placeholder="search"], input[type="text"]').first.click()
    page.wait_for_timeout(1000)
    baskets = [b.strip() for b in page.locator('mat-option').all_inner_texts()
               if b.strip() and b.strip() != "No results found"]
    print(f"  Nalezeno {len(baskets)} kosiku: {baskets}")
    page.keyboard.press("Escape")
    page.wait_for_timeout(500)

    if not baskets:
        print("  Zadne destruction kosite — preskakuji.")
        return

    for basket in baskets:
        filename = os.path.join(output_dir, f"ip_destruction_basket_{basket}.xlsx")
        if os.path.exists(filename):
            print(f"  [{basket}] Preskakuji — existuje.")
            continue
        print(f"  [{basket}] Stahuji...")
        input_field = page.locator('input[placeholder="search"], input[type="text"]').first
        input_field.click()
        input_field.fill(basket)
        page.wait_for_timeout(500)
        page.locator('mat-option').first.dispatch_event('click')
        page.wait_for_load_state("networkidle", timeout=120000)

        with page.expect_download(timeout=120000) as dl:
            page.get_by_role("button", name="Download XLS").click()
        dl.value.save_as(filename)
        print(f"  [{basket}] OK")

        page.get_by_role("button", name="Clear").click()
        page.wait_for_load_state("networkidle", timeout=120000)

    print("  Destruction hotovo.")


if __name__ == "__main__":
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(accept_downloads=True)
        page = context.new_page()
        page.goto(BASE_URL)
        page.wait_for_load_state("networkidle")
        page.get_by_label("Email *").fill(EMAIL)
        page.get_by_label("Password *").fill(PASSWORD)
        page.locator('#login__submit').click()
        page.wait_for_load_state("networkidle")
        page.get_by_label("Study *").click()
        page.get_by_role("option", name=STUDY).click()
        page.get_by_role("button", name="SELECT").click()
        page.wait_for_load_state("networkidle")
        run(page, STUDY)
        browser.close()
