import json
import requests

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

endpoint_cpt_kr1 = "https://kr1-api-instance-infrastructure.nhncloudservice.com"
endpoint_cpt_kr2 = "https://kr2-api-instance-infrastructure.nhncloudservice.com"
endpoint_img_kr1 = "https://kr1-api-image-infrastructure.nhncloudservice.com"
endpoint_img_kr2 = "https://kr2-api-image-infrastructure.nhncloudservice.com"


class ApiCompute:
    def __init__(self, region, tenant_id, token):
        if region == "kr1":
            self.cptUrl = endpoint_cpt_kr1
            self.imgUrl = endpoint_img_kr1
        elif region == "kr2":
            self.cptUrl = endpoint_cpt_kr2
            self.imgUrl = endpoint_img_kr2
        else:
            self.cptUrl = endpoint_cpt_kr2
            self.imgUrl = endpoint_img_kr2
        self.token = token
        self.tenantId = tenant_id

    def getFlavorList(self):
        url = f"{self.cptUrl}/v2/{self.tenantId}/flavors"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)
        return datas

    def getFlavorId(self, flavor_name):
        url = f"{self.cptUrl}/v2/{self.tenantId}/flavors"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)['flavors']

        for var in datas:
            foo = str(var['name'])
            if foo.count(flavor_name) == 1:
                return var['id']

    def getKeypairList(self):
        url = f"{self.cptUrl}/v2/{self.tenantId}/os-keypairs"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)
        return datas

    def getKeypairInfo(self, keypair_name):
        url = f"{self.cptUrl}/v2/{self.tenantId}/os-keypairs/{keypair_name}"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)
        return datas

    def InstanceList(self):
        pass

    def InstanceStatus(self, serverId):
        url = f"{self.cptUrl}/v2/{self.tenantId}/servers/{serverId}"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)['server']['status']
        return datas

    def InstanceInfo(self, serverId):
        url = f"{self.cptUrl}/v2/{self.tenantId}/servers/{serverId}"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)  # ['server']['status']
        return datas

    def InstanceId(self, instance_name):
        pass

    def deleteInstance(self, instance_id):
        pass

    def createInstance(self, instance_name, instance_image_id, flavor_id, subnet_id, kepair_name):
        url = f"{self.cptUrl}/v2/{self.tenantId}/servers"
        parms = {
            "server": {
                "name": instance_name,
                "imageRef": instance_image_id,
                "flavorRef": flavor_id,
                "networks": [
                    {
                        "subnet": f"{subnet_id}",
                    }
                ],
                # "availability_zone": "kr-pub-b",
                "key_name": kepair_name,
                "max_count": 1,
                "min_count": 1,
                "block_device_mapping_v2": [
                    {
                        "uuid": f"{instance_image_id}",
                        "boot_index": 0,
                        "volume_size": 50,
                        "device_name": "vda",
                        "source_type": "image",
                        "destination_type": "volume",
                        "delete_on_termination": 1,
                    }
                ],
                "security_groups": [{"name": "default"}],
            }
        }

        headers = {
            "X-Auth-Token": self.token,
        }
        # print(parms)
        response = requests.post(url, json=parms, headers=headers)
        datas = json.loads(response.text)['server']
        # print("------------------------")
        # print(response)
        # print("------------------------")
        # print(datas)
        return datas['id']

    def getImgListAll(self):
        url = f"{self.imgUrl}/v2/images"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)
        return datas

    def getInstanceImgId(self, img_name):
        url = f"{self.imgUrl}/v2/images"
        headers = {"X-Auth-Token": self.token}
        response = requests.get(url, headers=headers)
        datas = json.loads(response.text)['images']

        for var in datas:
            foo = str(var['name'])
            if foo.startswith(img_name) and foo.count("Container") == 0:
                return var['id']
