from django.shortcuts import render, redirect
from django.conf import settings
from .models import Cluster
from pathlib import Path
from django.core.files import File
import nhncloud.packages.ApiToken as ApiToken
from nhncloud.packages.ApiVpc import ApiVpc
from nhncloud.packages.ApiNks import ApiNks
from nhncloud.packages.ApiCompute import ApiCompute
from nhncloud.packages.ApiStorageObject import ApiStorageObject
from kubernetes import client, utils, config
import yaml
import time
import os
import json


# 공통 모듈
def getToken2(auth_dict):
    parms = {
        "auth": {
            "tenantId": auth_dict["tenantId"],
            "passwordCredentials": {
                "username": auth_dict["id"],
                "password": auth_dict["pw"],
            },
        }
    }

    # [Post] Create Token
    tokenDict = ApiToken.createToken(parms)

    token = str(tokenDict["tokenValue"])

    return token


# ---
def getTokenDict(tenantId, id, pw):
    parms = {
        "auth": {
            "tenantId": tenantId,
            "passwordCredentials": {"username": id, "password": pw},
        }
    }

    # [Post] Create Token
    tokenDict = ApiToken.createToken(parms)

    return tokenDict


def createToken(tenantId, id, pw):
    # Create Token request info
    parms = {
        "auth": {
            "tenantId": tenantId,
            "passwordCredentials": {"username": id, "password": pw},
        }
    }

    # [Post] Create Token
    tokenDict = ApiToken.createToken(parms)
    if tokenDict["state"] == "err":
        result = {
            "target": "tokenErr",
            "code": tokenDict["code"],
            "errTitle": tokenDict["errTitle"],
            "errMsg": tokenDict["errMsg"],
        }
        return result
    else:
        token = tokenDict["tokenValue"]

    return token


# 파일 생성테스트 모듈
def infoTemplateRequest(request):
    return render(request, "nhncloud/infoObjectStorageRequest.html", {})


def modelIndex(request):
    clusters = Cluster.objects.all().order_by("-pk")

    return render(
        request,
        "nhncloud/test.html",
        {
            "clusters": clusters,
        },
    )


def modelIndex_single(request, pk):
    cluster = Cluster.objects.get(pk=pk)
    return render(
        request,
        "nhncloud/single_test.html",
        {
            "cluster": cluster,
        },
    )


def fileUpload(request):
    # 참고자료 https://docs.djangoproject.com/en/5.0/topics/files/#file-storage
    # To save an existing file on disk to a FileField
    if request.method == "POST":
        postData = request.POST
        print(f"postData : {postData}")

        clusterName = request.POST["title"]

        cluster = Cluster(title=f"{clusterName}", content="demo")
        cluster.save()

        base_dir_path = os.path.dirname(__file__)
        configFilePath = f"{base_dir_path}/manifests/{clusterName}_config"
        with open(configFilePath, "w") as f:
            f.write("test-demo1")

        path = Path(configFilePath)

        fu = Cluster.objects.get(title=f"{clusterName}")
        with path.open(mode="rb") as f:
            fu.file_upload = File(f, name=path.name)
            fu.save()
        # print(path.name)
        # 업로드 후 임시 파일 삭제
        if os.path.exists(configFilePath):
            os.remove(configFilePath)

        return None
        # return render(
        #     request,
        #     'nhncloud/test.html',
        #     {
        #     }
    # )
    # rename 적용예정
    # 참고자료 : https://stackoverflow.com/questions/2680391/how-to-change-the-file-name-of-an-uploaded-file-in-django


def pythonRun(request):
    tmp = os.path.dirname(__file__)
    # print(__file__)
    # filePath = rf"{tmp}\string.yaml"
    filePath = f"{tmp}/manifests/lb_ingress.yaml"

    with open(filePath, "r", encoding="UTF8") as file:
        fileContents = file.readlines()

    return render(request, "nhncloud/pythonRun.html", {"rs": fileContents})


def nksApply(request):
    return render(request, "nhncloud/_rq_nks_components_apply.html", {})

def applyClusterLbRequest(request):
    return render(request, "nhncloud/applyClusterLbRequest.html", {})


def apiList(request):
    return render(request, "nhncloud/apiList.html", {})


def preparations(request):
    return render(request, "nhncloud/preparations.html", {})


def createVpcRequest(request):
    return render(request, "nhncloud/createVpcRequest.html", {})


def createClusterRequest(request):
    return render(request, "nhncloud/createClusterRequest.html", {})


def createClusterOnlyRequest(request):
    checkSearchVpc = request.POST.get("searchVpcList")

    listVpc = None
    subnetList = None
    
    if checkSearchVpc == "yes":
        vpcList = infoVpcList(request)
        listVpc = []
        for var in vpcList:
            listVpc.append({var["name"]: var["id"]})
        subnetList = json.loads(infoSubnetList(request))
        # print(type(subnetList))
        # print(subnetList)
    forward = {"vpcList": listVpc, "subnetList": subnetList}

    return render(request, "nhncloud/_rq_nks_create.html", forward)


def removeClusterRequest(request):
    return render(request, "nhncloud/removeClusterRequest.html", {})


def infoClusterListRequest(request):
    forward = {
        "nhnc_id": getattr(request.user, "nhnc_id", ""),
        "nhnc_api_tenant_id": getattr(request.user, "nhnc_api_tenant_id", ""),
    }

    return render(request, "nhncloud/infoClusterListRequest.html", forward)


def infoClusterDetailRequest(request):
    return render(request, "nhncloud/infoClusterDetailRequest.html", {})


def infoVpcListRequest(request):
    forward = {
        "nhnc_id": getattr(request.user, "nhnc_id", ""),
        "nhnc_api_tenant_id": getattr(request.user, "nhnc_api_tenant_id", ""),
    }

    return render(request, "nhncloud/_rq_vpc_list.html", forward)


def infoClusterDetail(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST

    clusterName = postData["clusterName"]
    regionName = postData["region"]
    tenantIdentity = postData["tenantId"]
    userEmail = postData["usrEmail"]
    userPasswd = postData["apiPw"]

    # Create Token request info
    parms = {
        "auth": {
            "tenantId": tenantIdentity,
            "passwordCredentials": {"username": userEmail, "password": userPasswd},
        }
    }

    print("### Token 호출: infoVpcList ###")
    auth_dict = {
        "tenantId": postData["tenantId"],
        "pw": postData["apiPw"],
        "id": postData["usrEmail"],
    }
    token = getToken2(auth_dict)

    nks = ApiNks(regionName, token)
    clusterInfo = nks.getClusterInfo(clusterName)
    print(clusterInfo)
    # print(clusterInfo['errors'][0])
    if "errors" in clusterInfo:
        result = {
            "target": "infoClusterErr",
            "clusterInfoStatus": clusterInfo["errors"][0]["status"],
            "clusterInfoTitle": clusterInfo["errors"][0]["title"],
            "clusterInfoDetail": clusterInfo["errors"][0]["detail"],
        }
    else:
        result = {
            "target": "infoClusterDetail",
            "clusterName": clusterInfo["name"],
            "clusterInfoStatus": clusterInfo["status"],
            "kubeConfig": "pending",
        }
    if result["clusterInfoStatus"] == "CREATE_COMPLETE":
        result.update({"kubeConfig": nks.getClusterConfig(clusterName)})
        configFile = result["kubeConfig"]
        # print(configFile)
        # with open("tmp_config", "w") as f:
        #     for i in configFile:
        #         f.write(i)
    return render(request, "nhncloud/resultRequest.html", result)


def infoVpcList(request):
    print("### VPC 조회 기능: infoVpcList ###")
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        # print(f"postData: {postData}")
        if "region" in postData:
            region = postData["region"]
        elif "region-pre" in postData:
            region = postData["region-pre"]
        else:
            pass

        if 'tenantId' in postData:
            tenantId =  postData['tenantId']
        elif 'tenantId-pre' in postData:
            tenantId =  postData['tenantId-pre']
        else:
            pass
    print("### Token 호출: infoVpcList ###")
    auth_dict = {
        "tenantId": tenantId,
        "pw": postData["apiPw"],
        "id": postData["usrEmail"],
    }
    token = getToken2(auth_dict)

    vpc = ApiVpc(region, token)
    print("### vpclist 호출: infoVpcList ###")
    vpcList = vpc.vpcList()["vpcs"]
    # print(f'vpclist ::: {vpcList}')
    i = len(vpcList) - 1
    # print(f"리스트개수 : {i}")
    for var in reversed(vpcList):
        # print(var['name'])
        if var["name"] == "Public Network":
            vpcList.pop(i)
            i -= 1
        else:
            if i == 0:
                break
            else:
                i -= 1

    result = {"vpcs": vpcList, "region": region}
    # Return Subnet List
    if "searchVpcList" in postData:
        return vpcList

    return render(request, "nhncloud/_rs_vpc_list.html", result)


def infoSubnetList(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST

        if "region" in postData:
            region = postData["region"]
        elif "region-pre" in postData:
            region = postData["region-pre"]
        else:
            pass

        if "tenantId" in postData:
            tenantId = postData["tenantId"]
        elif "tenantId-pre" in postData:
            tenantId = postData["tenantId-pre"]
        else:
            pass

        userEmail = postData["usrEmail"]
        apiPw = postData["apiPw"]
        subnetType = postData["subnetRadio"]
        print(subnetType)
    # Token create
    token = createToken(tenantId, userEmail, apiPw)

    print(f"[Post] Create Token : {token}")

    sbn = ApiVpc(region, token)

    subNetList = sbn.subnetList()["vpcsubnets"]
    i = len(subNetList) - 1
    # print(f"리스트개수 : {i}")
    for var in reversed(subNetList):
        # print(var['name'])
        if var["vpc"]["name"] == "Public Network":
            subNetList.pop(i)
            i -= 1
        else:
            if i == 0:
                break
            else:
                i -= 1

    publicSubnet = {}
    privateSubnet = {}
    for foo in subNetList:
        if "external_network_id" in foo["routingtable"]:
            publicSubnet.update(
                {foo["vpc"]["id"]: {"name": foo["name"], "id": foo["id"]}}
            )
        else:
            privateSubnet.update(
                {foo["vpc"]["id"]: {"name": foo["name"], "id": foo["id"]}}
            )
    # print(f'public::{publicSubnet}')
    # print(f'private::{privateSubnet}')
    if subnetType == "option1":
        subnet = publicSubnet
    else:
        subnet = privateSubnet

    jsonData = json.dumps(subnet)
    print(f"jsondata: {jsonData}")
    return jsonData


def createVpc(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        projectName = postData["taskName"]
        regionName = postData["region"]
        tenantIdentity = postData["tenantId"]
        userEmail = postData["usrEmail"]
        userPasswd = postData["apiPw"]
        vpcCidr4 = postData["vpcCidr"]
        subnetCidr4 = postData["subnetCidr"]
        internetGatewayId = postData["igwId"]
        #########################
        # API Endpoint Info
        tenantId = tenantIdentity  # Compute에서 확인
        # Create Token request info
        parms = {
            "auth": {
                "tenantId": tenantId,
                "passwordCredentials": {"username": userEmail, "password": userPasswd},
            }
        }
        # [Post] Create Token
        tokenDict = ApiToken.createToken(parms)
        if tokenDict["state"] == "err":
            result = {
                "target": "tokenErr",
                "code": tokenDict["code"],
                "errTitle": tokenDict["errTitle"],
                "errMsg": tokenDict["errMsg"],
            }
            return render(request, "nhncloud/resultRequest.html", result)
        else:
            token = tokenDict["tokenValue"]

        ############################
        # VPC 용 클래스
        vpc = ApiVpc(regionName, token)

        ############################
        # VPC 중복 검토
        vpcList = vpc.vpcList()["vpcs"]
        # print(f"리스트개수 : {i}")
        for var in reversed(vpcList):
            # print(var['name'])
            if var["name"] == projectName:
                result = {
                    "target": "vpcDuplicate",
                    "resultMsg": "VPC가 중복 되어 생성되지 않았습니다.",
                }
                return render(request, "nhncloud/resultRequest.html", result)
            elif var["cidrv4"] == vpcCidr4:
                result = {
                    "target": "vpcDuplicate",
                    "resultMsg": "VPC CIDR이 중복 되어 생성되지 않았습니다.",
                }
                return render(request, "nhncloud/resultRequest.html", result)
            else:
                pass

        # [Post] VPC create
        vpcId = vpc.vpcCreate(projectName, vpcCidr4)
        print(f"[Post] VPC create : {vpcId}")

        # [Post] VPC Subnet create
        subnetId = vpc.subnetCreate(vpcId, subnetCidr4, f"{projectName}-external_sbn")
        print(f"[Post] VPC Subnet create : {subnetId}")

        # [Post] Create Routing table
        defaultRoutingId = vpc.routingCreate(f"{projectName}-external_sbn-rt", vpcId)
        # print(f"기본라우팅테이블 아이디 {defaultRoutingId}")
        print(f"[Post] Create Routing table : {defaultRoutingId}")

        # [Put] Set Default Routing
        vpc.setDefaultRouting(defaultRoutingId)
        print("[Put] Set Default Routing")

        # [Get] Check Provisioning Routing
        print(f"[Get] Check Provisioning Routing...")
        routList = vpc.routingList()["routingtables"]
        routListIndex = 0
        for var in routList:
            print(var)
            vpcNm = str(var["vpcs"][0]["name"])
            vpcId = var["vpcs"][0]["id"]
            rtNm = str(var["name"])
            rtId = var["id"]

            if rtNm.startswith("vpc-") and vpcNm.startswith(projectName):
                routingId = rtId
            routListIndex += 1
        print(f"[Get] Check Provisioning Routing : {routingId}")

        # [Delete] init Routing Delete
        vpc.routingDelete(routingId)
        print(f"[Delete] init Routing Delete : {routingId}")

        # [Put] Set Internet gateway to routing-table
        rs = vpc.setIgwToRoutingTable(defaultRoutingId, internetGatewayId)
        print(f"[Put] Set Internet gateway to routing-table : {rs}")
        print("Network Configuration Complete.")

        return infoVpcList(request)


def infoClusterList(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        region = postData["region"]

    print("### Token 호출: infoVpcList ###")
    auth_dict = {
        "tenantId": postData["tenantId"],
        "pw": postData["apiPw"],
        "id": postData["usrEmail"],
    }
    token = getToken2(auth_dict)

    nks = ApiNks(region, token)
    clusterList = nks.getClusterList()["clusters"]
    print(f"클러스터리스트::: {clusterList}")
    
    convert_clusterList = []
    
    for tmp in clusterList:
        # del tmp['uuid']
        del tmp["cluster_template_id"]
        del tmp["docker_volume_size"]
        del tmp["uuid"]
        del tmp["labels"]
        del tmp["master_count"]
        del tmp["flavor_id"]
        del tmp["create_timeout"]
        del tmp["links"]
        del tmp["stack_id"]
        
        if tmp["status"] == "CREATE_COMPLETE":
            kubeconfig = nks.getClusterConfig(tmp["name"])
            tmp["kubeconfig"] = kubeconfig
        
        convert_clusterList.append(tmp)
        
    result = {
        "clusters": convert_clusterList,
        "region": region,
    }
    return render(request, "nhncloud/_rs_nks_list.html", result)


def createCluster(request):
    
    nks_version = "v1.30.3"
    
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        print(f"requestValues: {postData}")
    projectName = postData["taskName"]
    regionName = postData["region"]
    keyPairName = postData["KeyPair"]
    tenantIdentity = postData["tenantId"]
    userEmail = postData["usrEmail"]
    userPasswd = postData["apiPw"]
    vpcCidr4 = postData["vpcCidr"]
    subnetCidr4 = postData["subnetCidr"]
    internetGatewayId = postData["igwId"]

    ### Define parameters ###
    infraCiCd = {
        "igwId": internetGatewayId,
        "tenantId": tenantIdentity,
        "username": userEmail,
        "passwd": userPasswd,
        "vpcName": f"{projectName}-vpc",
        "vpcCidr": vpcCidr4,
        "subnetCidr": subnetCidr4,
        "region": regionName,  # 평촌 : kr2 | 판교 : kr1
        "clusterName": f"{projectName}-cluster",
        "kepair_name": keyPairName,
        "flavorName": "m2.c4m8",
    }
    # API Endpoint Info
    tenantId = infraCiCd["tenantId"]  # Compute에서 확인
    userEmail = infraCiCd["username"]
    apiPw = infraCiCd["passwd"]
    # Resource Info
    igwId = infraCiCd["igwId"]  # Network에서 확인 스크립트 실행 전 먼저 생성 필요.
    vpcName = infraCiCd["vpcName"]
    vpcCidr = infraCiCd["vpcCidr"]
    subnetCidr = infraCiCd["subnetCidr"]
    region = infraCiCd["region"]
    clusterName = infraCiCd["clusterName"]
    
    print("### Token 호출: infoVpcList ###")
    auth_dict = {
        "tenantId": postData["tenantId"],
        "pw": postData["apiPw"],
        "id": postData["usrEmail"],
    }
    token = getToken2(auth_dict)

    # VPC 용 클래스
    vpc = ApiVpc(region, token)
    # VPC 중복 검토
    vpcList = vpc.vpcList()["vpcs"]
    # print(f"리스트개수 : {i}")
    for var in reversed(vpcList):
        # print(var['name'])
        if var["name"] == f"{projectName}-vpc":
            result = {
                "target": "vpcDuplicate",
                "resultMsg": "VPC가 중복 되어 생성되지 않았습니다.",
            }
            return render(request, "nhncloud/resultRequest.html", result)
        elif var["cidrv4"] == vpcCidr4:
            result = {
                "target": "vpcDuplicate",
                "resultMsg": "VPC CIDR이 중복 되어 생성되지 않았습니다.",
            }
            return render(request, "nhncloud/resultRequest.html", result)
        else:
            pass

    # [Post] VPC create
    vpcId = vpc.vpcCreate(vpcName, vpcCidr)
    print(f"[Post] VPC create : {vpcId}")

    # [Post] VPC Subnet create
    subnetId = vpc.subnetCreate(vpcId, subnetCidr, f"{vpcName}-external_sbn")
    print(f"[Post] VPC Subnet create : {subnetId}")

    # [Post] Create Routing table
    defaultRoutingId = vpc.routingCreate(f"{vpcName}-external_sbn-rt", vpcId)
    # print(f"기본라우팅테이블 아이디 {defaultRoutingId}")
    print(f"[Post] Create Routing table : {defaultRoutingId}")

    # [Put] Set Default Routing
    vpc.setDefaultRouting(defaultRoutingId)
    print("[Put] Set Default Routing")

    # [Get] Check Provisioning Routing
    print(f"[Get] Check Provisioning Routing...")
    routList = vpc.routingList()["routingtables"]
    routListIndex = 0
    for var in routList:
        print(var)
        vpcNm = str(var["vpcs"][0]["name"])
        vpcId = var["vpcs"][0]["id"]
        rtNm = str(var["name"])
        rtId = var["id"]

        if rtNm.startswith("vpc-") and vpcNm.startswith(vpcName):
            routingId = rtId
        routListIndex += 1
    print(f"[Get] Check Provisioning Routing : {routingId}")

    # [Delete] init Routing Delete
    vpc.routingDelete(routingId)
    print(f"[Delete] init Routing Delete : {routingId}")

    # [Put] Set Internet gateway to routing-table
    rs = vpc.setIgwToRoutingTable(defaultRoutingId, igwId)
    print(f"[Put] Set Internet gateway to routing-table : {rs}")
    print("Network Configuration Complete.")

    # exvid 테스트 nks구성시 사용.
    exVpc = vpc.getExternalNetworkId()
    exVpcId = exVpc["networks"][0]["id"]
    exVpcTemp = exVpc["networks"][0]["subnets"]
    exSubnetList = ":".join(exVpcTemp)
    print(exVpcId)
    print(exSubnetList)

    cpt = ApiCompute(infraCiCd["region"], infraCiCd["tenantId"], token)

    flavorId = cpt.getFlavorId(infraCiCd["flavorName"])

    nks = ApiNks(infraCiCd["region"], token)

    parms_dict = {
        "cluster_name": clusterName,
        "vpc_id": vpcId,
        "subnet_id": subnetId,
        "instance_type": flavorId,
        "key_pair": infraCiCd["kepair_name"],
        "az-zone": "kr2-pub-b",
        "kubernetes-version": nks_version,
        "nd_cnt": 3,
        "external_network_id": exVpcId,
        "external_subnet_id_list": exSubnetList,
    }
    # [Post] Create Cluster
    nks.publicClusterCreate(parms_dict)
    print(f"[Post] Create Cluster...")

    return infoClusterList(request)


def createOnlyCluster(request):
    
    nks_version = "v1.30.3"
    
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        print(f"requestValues: {postData}")

    flavorName = "m2.c4m8"

    # Create Token request info
    vpcId = postData["vpc"]
    publicSubnetId = postData["publicSubnet"]
    region = postData["region"]
    clusterName = postData["clusterName"]
    keyPairName = postData["KeyPair"]
    tenantId = postData["tenantId"]
    if region == "kr1":
        azZone = "kr"
    else:
        azZone = region

    print("### Token 호출: infoVpcList ###")
    auth_dict = {
        "tenantId": tenantId,
        "pw": postData["apiPw"],
        "id": postData["usrEmail"],
    }
    token = getToken2(auth_dict)

    print(f"[Post] Create Token : {token}")

    # VPC 용 클래스
    vpc = ApiVpc(region, token)
    # exvid .
    exVpc = vpc.getExternalNetworkId()
    exVpcId = exVpc["networks"][0]["id"]
    exVpcTemp = exVpc["networks"][0]["subnets"]
    exSubnetList = ":".join(exVpcTemp)

    cpt = ApiCompute(region, tenantId, token)

    flavorId = cpt.getFlavorId(flavorName)
    # print(f"flavorId : {flavorId}")
    nks = ApiNks(region, token)

    print("Cluster Create Check")
    if Cluster.objects.filter(title=clusterName, type="nks").exists():
        print("exist name")
        return render(
                request,
                'nhncloud/_rs_err.html',
                {
                    'resultMsg' : "중복된 이름의 클러스터가 있습니다."
                }
            ) 
    else:
        parms_dict = {
            "cluster_name": clusterName,
            "vpc_id": vpcId,
            "subnet_id": publicSubnetId,
            "instance_type": flavorId,
            "key_pair": keyPairName,
            "az-zone": f"{azZone}-pub-b",
            "kubernetes-version": nks_version,
            "nd_cnt": 3,
            "external_network_id": exVpcId,
            "external_subnet_id_list": exSubnetList,
        }
        # [Post] Create Cluster
        nks.publicClusterCreate(parms_dict)
        # DB에 등록
        Cluster.objects.create(
            title=clusterName,
            type="nks"
        )
        
        print(f"[Post] Create Cluster...")
        time.sleep(2)
        
        return infoClusterList(request)


def removeCluster(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST

    clusterName = postData["clusterName"]
    regionName = postData["region"]
    tenantId = postData["tenantId"]
    userEmail = postData["usrEmail"]
    apiPw = postData["apiPw"]

    # Token create
    token = createToken(tenantId, userEmail, apiPw)

    print(f"[Post] Create Token : {token}")

    nks = ApiNks(regionName, token)

    # [Delete] Delete Cluster
    nks.nksDelete(clusterName)
    print(f"[Delete] Delete ClusterName : {clusterName}")
    # database remove data
    clusterListCount = len(
        Cluster.objects.filter(title=f"{clusterName}")
    )  # uuid 정보도 추가되야됨
    if clusterListCount >= 1:
        fu = Cluster.objects.get(title=clusterName)
        fu.delete()
    print(f"[Delete] remove data in db : {clusterName}")
    
    return infoClusterList(request)


def removeVpc(request):
    print("[start] removeVpc")
    # input property is name.
    if request.method == "POST":
        postData = request.POST
    print(postData)
    igwInclude = postData["igwRadios"]  # option1 : include | option2 : detach
    regionName = postData["region"]
    vpcName = postData["vpcName"]

    # Resource Info
    region = regionName

    print('### Token 호출: infoVpcList ###')
    auth_dict = {
        'tenantId' : postData['tenantId'],
        'pw' : postData['apiPw'],
        'id' : postData['usrEmail']
    }
    token = getToken2(auth_dict)

    print(f"[Post] Create Token : {token}")

    vpc = ApiVpc(region, token)
    vpcId = vpc.getVpcId(vpcName)
    if vpcId == "onlyOne":
        return render(
            request,
            "nhncloud/resultRequest.html",
            {"resultMsg": "삭제 대상이 없습니다. 리전을 확인해주세요."},
        )
    # [Put] Detach Igw
    if igwInclude == "option2":
        print(f"[Put] Detach Igw")
        subnetList = vpc.subnetList()["vpcsubnets"]
        i = len(subnetList) - 1
        # print(f"리스트개수 : {i}")
        for foo in reversed(subnetList):
            # print(f"1st :: {subnetList}")
            if foo["vpc"]["name"] == "Public Network":
                subnetList.pop(i)
                i -= 1
                # print(f"For :: {subnetList}")
            else:
                if i == 0:
                    break
                else:
                    i -= 1
        for subnet in subnetList:
            if subnet["vpc"]["id"] == vpcId:
                routingTable = subnet["routingtable"]
                if "gateway_id" in routingTable:
                    print(routingTable["gateway_id"])  # igw id value.
                    rs = vpc.detachIgwFromRoutingTable(routingTable["id"])
                    print(rs)
    # [Delete] Delete vpc
    print(f"[Delete] Delete vpc : {vpcId} 관련 리소스를 삭제합니다.")
    vpc.vpcDelete(vpcId)
    return infoVpcList(request)


def kubectlApplyLB(request):
    ### [get] kube config ###
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        region = postData["region"]
        
    clusterName = postData["clusterName"]
    floatingIP = postData["floatingIP"]
    loadbalancerName = postData["loadBancerName"]
    targetIP = "floatingIP"
    targetName = "loadbalancerName"

    print("LB Create Check")
    if Cluster.objects.filter(title=loadbalancerName, type="lb").exists():
        print("exist name")
        return render(
                request,
                'nhncloud/_rs_err.html',
                {
                    'resultMsg' : "중복된 이름의 LB가 있습니다."
                }
            ) 
    else:
        base_dir_path = os.path.dirname(__file__)
        
        print("### Token 호출: infoVpcList ###")
        auth_dict = {
            "tenantId": postData["tenantId"],
            "pw": postData["apiPw"],
            "id": postData["usrEmail"],
        }
        token = getToken2(auth_dict)
        
        nks = ApiNks(region, token)
        kubeconfig = nks.getClusterConfig(clusterName)

        ### [Change] lb.yaml ###
        print("lb 설정 시작")
        filePath = f"{base_dir_path}/manifests/lb_ingress.yaml"

        print("lb 파일읽기")
        with open(filePath, "r") as file:
            fileContents = file.readlines()
        # print("lb 플로팅아이피 변경")
        # with open(filePath, "w") as file:
        #     for i in fileContents:
        #         file.write(i.replace(targetIP, floatingIP))
        print("lb 파일읽기")
        with open(filePath, "r") as file:
            fileContents = file.readlines()
        print("lb 이름 변경")
        with open(filePath, "w") as file:
            for i in fileContents:
                file.write(i.replace(targetName, loadbalancerName))

        print("lb이름 설정 끝")
        # ###########################################################
        kubeconfig_dict = yaml.safe_load(kubeconfig)
        config.load_kube_config_from_dict(kubeconfig_dict)
        k8s_client = client.ApiClient()
        yaml_file = filePath
        utils.create_from_yaml(k8s_client, yaml_file, verbose=True)
        ###########################################################
        ### [return] lb.yaml ###
        print("lb 설정 시작")
        with open(filePath, "r") as file:
            fileContents = file.readlines()

        # with open(filePath, "w") as file:
        #     for i in fileContents:
        #         file.write(i.replace(floatingIP, targetIP))

        # with open(filePath, "r") as file:
        #     fileContents = file.readlines()

        with open(filePath, "w") as file:
            for i in fileContents:
                file.write(i.replace(loadbalancerName, targetName))

        # DB에 등록
        Cluster.objects.create(
            title=loadbalancerName,
            type="lb"
        )
        
        
        return render(
            request,
            "nhncloud/_rs_nks_deploy.html",
            {"resultMsg": "약 10분 이내로 ingress 용 로드밸런서가 생성 됩니다."},
        )


########################################
###          Object Storage          ###
########################################


def infoObjectStorageRequest(request):
    return render(request, "nhncloud/infoObjectStorageRequest.html", {})


# 20240123 Get List
def infoObjectStorageList(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        region = postData["region"]
    print(f"넘겨받는값: {postData}")
    # Create Token request info
    tenantId = postData["tenantId"]
    userEmail = postData["usrEmail"]
    apiPw = postData["apiPw"]
    storageAccount = postData["objStrgAccount"]
    if storageAccount == "None":
        return render(
            request,
            "nhncloud/resultRequest.html",
            {"resultMsg": "Object Storage의 Service Account 정보가 없습니다."},
        )
    # [Post] Create Token
    token = createToken(tenantId, userEmail, apiPw)

    print(f"[Post] Create Token : {token}")

    obstrg = ApiStorageObject(region, token, storageAccount)
    objectStorageList = obstrg.get_container_list()
    listCount = len(objectStorageList) - 1
    objectStorageList.pop(listCount)
    print(f"obstrg>> {objectStorageList}")
    result = {
        "target": "objectStorageList",
        "objectList": objectStorageList,
        "region": region,
    }
    return render(request, "nhncloud/resultRequest.html", result)


# 20240125 Delete
def removeObjectStorage(request):
    # input property is name.
    if request.method == "POST":
        postData = request.POST
        print(postData)

    objStorageName = postData["objStorageNameId"]
    regionName = postData["region"]
    tenantId = postData["tenantId"]
    userEmail = postData["usrEmail"]
    storageAccount = postData["objStrgAccount"]
    apiPw = postData["apiPw"]

    # Token create
    token = createToken(tenantId, userEmail, apiPw)

    print(f"[Post] Create Token : {token}")

    ostrg = ApiStorageObject(regionName, token, storageAccount)

    # [Delete] Delete Cluster

    objectList = ostrg._get_list(objStorageName)
    print(f"objectList:::::::::::::::::::\n {objectList}")
    for var in objectList:
        print(ostrg.delete(objStorageName, var))

    print(f"[Delete] Delete Object StorageName : {objStorageName}")

    return infoObjectStorageList(request)


def createObjectStorageRequest(request):
    pass


def createObjectStorage(request):
    pass
