# (c) cavaliba.com - tests / helper_data

import yaml

from app_data.loader import load_broker


def add_test_sites(count=5):
    yaml_entries = []
    for i in range(1, count + 1):
        yaml_entries.append(f"""- classname: site
  keyname: site{i:02d}
  displayname: Site {i:02d}""")
    yaml_str = "\n".join(yaml_entries)
    datalist = yaml.safe_load(yaml_str)
    aaa = {"perms": ["p_data_create", "p_data_site_admin"]}
    _ = load_broker(datalist=datalist, aaa=aaa)


def add_test_apps(count=5):
    yaml_entries = []
    for i in range(1, count + 1):
        yaml_entries.append(f"""- classname: app
  keyname: app{i:02d}
  displayname: App {i:02d}""")
    yaml_str = "\n".join(yaml_entries)
    datalist = yaml.safe_load(yaml_str)
    aaa = {"perms": ["p_data_create", "p_data_app_admin"]}
    _ = load_broker(datalist=datalist, aaa=aaa)


def add_schema(
    classname="unittest",
    action="create",
    displayname=None,
    options=None,
    field_definition=None,
    verbose=False,
):
    if displayname is None:
        displayname = classname

    yaml_entry = {
        "classname": "_schema",
        "_action": action,
        "keyname": classname,
        "displayname": displayname,
    }

    if options:
        yaml_entry["_options"] = options

    if field_definition:
        yaml_entry.update(field_definition)

    datalist = [yaml_entry]
    aaa = {
        "perms": [
            "p_schema_write",
        ]
    }
    load_broker(datalist=datalist, aaa=aaa)

    from app_data.schema import Schema

    return Schema.from_name(classname)


def add_instance(classname=None, keyname=None, action="create", fields=None, verbose=False):
    yaml_entry = {"classname": classname, "_action": action, "keyname": keyname}

    if fields:
        yaml_entry.update(fields)

    datalist = [yaml_entry]

    aaa = {
        "perms": [
            "p_data_admin",
        ]
    }

    load_broker(datalist=datalist, aaa=aaa)


def add_schema_field(classname="test", fields={}, verbose=False):
    yaml_entry = {"classname": "_schema", "keyname": classname}

    # Add the field definitions directly to the schema entry
    # field_definition should be a dict like: {'field1': {...}, 'field2': {...}}
    yaml_entry.update(fields)

    datalist = [yaml_entry]

    aaa = {
        "perms": [
            "p_schema_write",
        ]
    }
    load_broker(datalist=datalist, aaa=aaa)
