import json
import requests
import yaml

# type : network
# Region : 
#   판교: https://kr1-api-kubernetes-infrastructure.nhncloudservice.com
#   평촌: https://kr2-api-kubernetes-infrastructure.nhncloudservice.com

endpoint_kr1 = "https://kr1-api-kubernetes-infrastructure.nhncloudservice.com"
endpoint_kr2 = "https://kr2-api-kubernetes-infrastructure.nhncloudservice.com"

class ApiNks:
  def __init__(self, region, token):
    if region == "kr1" :
      self.region = region
      self.url = endpoint_kr1
    elif region == "kr2" :
      self.region = region
      self.url = endpoint_kr2
    else:
      self.region = region
      self.url = endpoint_kr2
    self.token = token
  
  
  def getClusterList(self):
    url = f"{self.url}/v1/clusters"
    headers={
      "X-Auth-Token": self.token,
      "Accept": "application/json",
      "Content-Type": "application/json",
      "OpenStack-API-Version": "container-infra latest"
    }
    response = requests.get(url, headers=headers)
    datas = json.loads(response.text)
    return datas
  
  def getClusterInfo(self, cluster_name):
    url = f"{self.url}/v1/clusters/{cluster_name}"
    headers={
      "X-Auth-Token": self.token,
      "Accept": "application/json",
      "Content-Type": "application/json",
      "OpenStack-API-Version": "container-infra latest"
    }
    response = requests.get(url, headers=headers)
    datas = json.loads(response.text)
    return datas
  
  def publicClusterCreate(self, parms_dict):
    print(f"리전정보 {self.region}")
    if self.region == "kr1" :
      node_img = "1213d033-bdf6-4d73-9763-4e8e57c745fb" # ubuntu 20.04
    elif self.region == "kr2" :
      node_img = "dabb6d10-937d-4952-9ce0-1e576e9164e8" # ubuntu 20.04
    else:
      node_img = "dabb6d10-937d-4952-9ce0-1e576e9164e8" # ubuntu 20.04
      
    url = f"{self.url}/v1/clusters"
    parms = {
      "cluster_template_id": "iaas_console",
      "create_timeout": 60,
      "fixed_network": str(parms_dict["vpc_id"]),
      "fixed_subnet": str(parms_dict["subnet_id"]),
      "flavor_id": str(parms_dict["instance_type"]),
      "keypair": str(parms_dict["key_pair"]),
      "labels": {
          "availability_zone": str(parms_dict["az-zone"]),
          "boot_volume_size": "50",
          "boot_volume_type": "General SSD",
          "ca_enable": "false",
          # "ca_max_node_count": "10",
          # "ca_min_node_count": "1",
          # "ca_scale_down_delay_after_add": "10", # 샘플은3인데 왜 10일 요구하나
          # "ca_scale_down_enable": "true",
          # "ca_scale_down_unneeded_time": "3",
          # "ca_scale_down_util_thresh": "50",
          # "cert_manager_api": "True",
          "cert_manager_api": "True",
          "clusterautoscale": "nodegroupfeature",
          "external_network_id": str(parms_dict["external_network_id"]), # 외부 연결된경우 적용
          "external_subnet_id_list": str(parms_dict["external_subnet_id_list"]), # 외부 연결
          "kube_tag": str(parms_dict["kubernetes-version"]),
          "master_lb_floating_ip_enabled": "True", # external_network, subnet적용시 True가능.
          "node_image": node_img,
          # "user_script_v2": ""
      },
      "name": str(parms_dict["cluster_name"]),
      "node_count": str(parms_dict["nd_cnt"])
    }
    
    headers={
      "Accept": "application/json",
      "Content-Type": "application/json",
      "OpenStack-API-Version": "container-infra latest",
      "X-Auth-Token": self.token
    }
    response = requests.post(url, json=parms, headers=headers)
    print(f"debug:{response}")
    datas = json.loads(response.text)
    # print("------------------------")
    # print(response)
    # print("------------------------")
    print(datas)
    return datas
  
  def privateClusterCreate(self, parms_dict):
    if self.region == "kr1" :
      node_img = "1213d033-bdf6-4d73-9763-4e8e57c745fb" # ubuntu 20.04
    elif self.region == "kr2" :
      node_img = "dabb6d10-937d-4952-9ce0-1e576e9164e8" # ubuntu 20.04
    else:
      node_img = "dabb6d10-937d-4952-9ce0-1e576e9164e8" # ubuntu 20.04

    url = f"{self.url}/v1/clusters"
    parms = {
      "cluster_template_id": "iaas_console",
      "create_timeout": 60,
      "fixed_network": str(parms_dict["vpc_id"]),
      "fixed_subnet": str(parms_dict["subnet_id"]),
      "flavor_id": str(parms_dict["instance_type"]),
      "keypair": str(parms_dict["key_pair"]),
      "labels": {
          "availability_zone": str(parms_dict["az-zone"]),
          "boot_volume_size": "50",
          "boot_volume_type": "General SSD",
          "ca_enable": "false",
          "cert_manager_api": "True",
          "clusterautoscale": "nodegroupfeature",
          "kube_tag": str(parms_dict["kubernetes-version"]),
          "master_lb_floating_ip_enabled": "False", # external_network, subnet적용시 True가능.
          "node_image": node_img,
      },
      "name": str(parms_dict["cluster_name"]),
      "node_count": str(parms_dict["nd_cnt"])
    }
    
    headers={
      "Accept": "application/json",
      "Content-Type": "application/json",
      "OpenStack-API-Version": "container-infra latest",
      "X-Auth-Token": self.token
    }
    response = requests.post(url, json=parms, headers=headers)
    datas = json.loads(response.text)
    # print("DEBUG MODE")
    # print(response)
    # print("DEBUG MODE")
    # print(datas)
    return datas
  
  def nksDelete(self, cluster_name):
    url = f"{self.url}/v1/clusters/{cluster_name}"
    headers={
      "X-Auth-Token": self.token,
      "Accept": "application/json",
      "Content-Type": "application/json",
      "OpenStack-API-Version": "container-infra latest"
    }
    response = requests.delete(url, headers=headers)
    
    return
  
  def getClusterConfig(self, cluster_name): # 작성만 하였음 확인 필요.
    url = f"{self.url}/v1/clusters/{cluster_name}/config"
    headers={
      "X-Auth-Token": self.token,
      "Accept": "application/json",
      "Content-Type": "application/json",
      "OpenStack-API-Version": "container-infra latest"
    }
    response = requests.get(url, headers=headers)
    datas = json.loads(response.text)
    return datas['config']  