import dataiku
DATAFRAMES_READING_CHUNKSIZE = 20


def switch_recipe_input(project, recipe_name, replacing_dataset_name):
    recipe = project.get_recipe(recipe_name)
    recipe_definition_and_payload = recipe.get_definition_and_payload()
    recipe_definition_and_payload.recipe_settings["inputs"]["main"]["items"][0]["ref"] = replacing_dataset_name
    recipe.set_definition_and_payload(recipe_definition_and_payload)
    pass

def build_dataset(project, dataset_name):
    dataset = project.get_dataset(dataset_name)
    dataset.build(job_type='NON_RECURSIVE_FORCED_BUILD')
    pass

def update_recipe_ouput_schema(project, recipe_name):
    recipe = project.get_recipe(recipe_name)
    required_updates = recipe.compute_schema_updates()
    if required_updates.any_action_required():
        required_updates.apply()
        pass
    pass

def get_current_project_and_variables():
    project_key = dataiku.get_custom_variables()["projectKey"]
    client = dataiku.api_client()
    project = client.get_project(project_key)
    variables = project.get_variables()
    return project, variables

def get_flow_zone_id(flow_zone_name):
    project_key = dataiku.get_custom_variables()["projectKey"]
    client = dataiku.api_client()
    project = client.get_project(project_key)
    flow = project.get_flow()
    flow_zones = flow.list_zones()
    n_flow_zones = len(flow_zones)
    
    for index, flow_zone in enumerate(flow_zones):
        if flow_zone.name == flow_zone_name:
            return flow_zone.id
        else:
            if index == n_flow_zones-1:
                return None
    pass

def move_dataset_in_flow_zone(project, dataset_name, flow_zone_name):
    flow_zone_id = get_flow_zone_id(flow_zone_name)
    if not (flow_zone_id is None):
        project_dataset = project.get_dataset(dataset_name)
        project_dataset.move_to_zone(flow_zone_id)
        pass
    pass