#!/usr/bin/env python3


import adhesive
from adhesive.workspace.kube.api import KubeApi
import yaml
import os
import addict


RESOURCE_TYPES = {
    "pod": "Pod",
    "service": "Service",
    "deploy": "Deployment",
    "cm": "ConfigMap",
    "secret": "Secret",
}



@adhesive.task('Read current data')
def read_current_data(context):
    # read the contexts
    with open(os.path.join(os.getenv('HOME'), '.kube', 'config'), "r") as f:
        kube_config = addict.Dict(yaml.safe_load(f))

    current_context_name = str(kube_config.get('current-context'))
    context.data.kube_context = str(kube_config.get('current-context'))
    context.data.kube_contexts = [it.name for it in kube_config.contexts]

    for ktx in kube_config.contexts:
        if ktx.name == current_context_name:
            current_context = ktx
            break

    context.data.kube_namespace = current_context["context"].get("namespace", "default")

    kubeapi = KubeApi(context.workspace, namespace=context.data.kube_namespace)
    try:
        namespaces = kubeapi.getall(kind="ns")
    except Exception:
        namespaces = [addict.Dict({"metadata": {"name": context.data.kube_namespace}})]

    context.data.kube_namespaces = [it.metadata.name for it in namespaces]

    resources = kubeapi.getall(kind=context.data.kube_resource_type)
    context.data.kube_resources = [it.metadata.name for it in resources]


@adhesive.usertask('Select resource')
def select_resource(context, ui):
    ui.add_combobox("kube_context",
            title="Context",
            value=context.data.kube_context,
            values=context.data.kube_contexts)
    ui.add_combobox("kube_namespace",
            title="Namespace",
            value=context.data.kube_namespace,
            values=context.data.kube_namespaces)
    ui.add_combobox("kube_resource_type",
            title="Type",
            values=RESOURCE_TYPES,
            value=context.data.kube_resource_type)
    ui.add_radio_group("kube_resources",
            title=RESOURCE_TYPES[context.data.kube_resource_type],
            values=context.data.kube_resources)


@adhesive.task('Select namespace if needed')
def select_namespace_if_needed(context):
    if context.data.original_kube_context != context.data.kube_context:
        # change context
        return

    if context.data.original_kube_namespace != context.data.original_kube_namespace:
        # change namespace
        context.data.namespace_changed = True



@adhesive.task('Edit selected resources')
def edit_selected_resources(context):
    context.workspace.run(f"""
        kubectl edit {context.data.kube_resource_type} {context.data.kube_resources}
    """)

adhesive.process_start()\
    .task("Read current data")\
    .usertask("Select resource")\
    .task("Select namespace if needed")\
    .task("Edit selected resources")\
    .process_end()\
    .build(initial_data={
        "kube_resource_type": "pod",
    })
