# -*-coding:UTF-8 -*-
import utils.common.log as logger


class ResponseParse(object):
    def __init__(self, res):
        self.res = res

    def get_res_code(self):
        status_code = self.res.status_code
        error_code = -1
        error_des = "failed"
        if status_code == 200:
            res = self.res.json()
            error_code = res['result']['code']
            error_des = res['result']['description']
            if error_des is None or error_code == 0:
                error_des = "success"
        return status_code, int(error_code), error_des

    def get_login_token(self):
        res = self.res.json()
        return res['data']['x_auth_token']

    def get_system_esn(self):
        res = self.res.json()
        return res['data']['system_esn']

    def get_data_status(self):
        res = self.res.json()
        return int(res.status_code)

    def get_res_data(self):
        res = self.res.json()
        if res.get('data'):
            return res.get('data').get('task_status'), \
                   res.get('data').get('server_result')
        else:
            return None, None

    def get_query_code(self):
        result = self.res.json()
        status_code = result.get('result')
        return status_code, result.get('errorCode'), result.get('description')

    def get_query_detail(self):
        result = self.res.json()
        return result.get('result'), result.get('detail')

    def get_query_data(self):
        return self.res.json()

    def get_all_media(self):
        res = self.res.json()
        return res.get('servers'), res.get('failedServers')

    def get_media_by_node(self, node):
        res = self.res.json()
        if res.get('servers'):
            node_media = res.get('servers').get(node)
        else:
            node_media = None
        return node_media

    def get_media_by_node_slot(self, node, slot, flash_type):
        res = self.res.json()
        disk_media = dict()
        disk_list = list()
        if res.get('servers'):
            for disk in res.get('servers').get(node):
                if disk.get('phySlotId') == int(slot):
                    disk_list.append(disk)
        # 由于缓存盘的槽位号是自动生成的，有可能出现缓存盘跟元数据盘槽位号相同的情况
        # 当一个槽位对应多个盘时，如果存储池非全闪，元数据盘则必须非ssd_disk/ssd_card,
        # 如果存储池为全闪，元数据盘不限制，全闪要求全ssd_disk或者全ssd_card
        # ssd_disk或ssd_card混合的全闪为非标准配置，出现ssd_card和ssd_disk槽位相同的情况不处理
        disk_len = len(disk_list)
        if disk_len > 1:
            for disk in disk_list:
                if flash_type:
                    err_msg = "In all-flash scenarios, only ssd disks or all" \
                              " ssd cards are supported. The current" \
                              " metadata node[%s] has two disks in the same" \
                              " slot. The ssd card and ssd disk may be used" \
                              " together" % node
                    logger.error(err_msg)
                    raise Exception(err_msg)
                media_type = disk.get('mediaType')
                if media_type not in ['ssd_disk', 'ssd_card'] and \
                        media_type != 'none':
                    disk_media = disk
                    break
        elif disk_len == 1:
            disk_media = disk_list[0]
        else:
            disk_media = None
        return disk_media

    def get_disks_by_node(self, node):
        res = self.res.json()
        node_disks = dict()
        if res.get('disks'):
            node_disks = res.get('disks').get(node)
        return node_disks

    def get_disks_by_node_slot(self, node, slot):
        res = self.res.json()
        disk_list = list()
        node_disks = dict()
        if res.get('disks'):
            for disks in res.get('disks').get(node):
                if disks.get('devSlot') == int(slot):
                    disk_list.append(disks)
        # 由于缓存盘的槽位号是自动生成的，有可能出现缓存盘跟主存盘槽位号相同的情况
        # 当一个槽位对应多个盘时，过滤掉缓存盘
        disk_len = len(disk_list)
        if disk_len > 1:
            for disk in disk_list:
                if disk.get('devType') not in ['ssd_disk', 'ssd_card']:
                    node_disks = disk
                    break
        elif disk_len == 1:
            node_disks = disk_list[0]
        else:
            node_disks = None
        return node_disks

    def get_create_pool_code(self):
        status_code = self.res.status_code
        result = None
        task_id = None
        error_code = -1
        error_des = "failed"
        if status_code == 200:
            res = self.res.json()
            task_id = res.get('task_id')
            result = res.get('result')
            error_code = res.get('errorCode')
            if error_code is None:
                error_code = 0
            error_des = res.get('description')
            if error_des is None or error_code == 0:
                error_des = "success"
        return status_code, result, task_id, error_code, error_des

    def get_expand_pool_code(self):
        return self.get_create_pool_code()

    def get_task_by_id(self, task_id):
        res = self.res.json()
        task_info = dict()
        all_tasks = res.get('taskInfo')
        for task in all_tasks:
            if task.get('taskId') == task_id:
                task_info = task
        return task_info

    def get_create_client_code(self):
        status_code = self.res.status_code
        result = -1
        error_code = -1
        error_des = "failed"
        if status_code == 200:
            res = self.res.json()
            result = res.get('result')
            if result == 0:
                error_code = 0
                error_des = 'success'
            elif result == 1:
                error_des = res.get('detail')
            else:
                error_code = res.get('errorCode')
                error_des = res.get('description')
        return status_code, result, int(error_code), error_des

    def get_nodes_data(self):
        status_code = self.res.status_code
        ret_code = -1
        ret_data = None
        if status_code == 200:
            ret_code = 0
            ret_data = self.res.json()
        return ret_code, ret_data

    def get_rsp_data(self):
        status_code = self.res.status_code
        rsp_code = -1
        ret_result = None
        ret_data = None
        if status_code == 200:
            rsp_code = 0
            if "result" in self.res.json():
                ret_result = self.res.json().get('result')
            elif "error" in self.res.json():
                ret_result = self.res.json().get('error')
            ret_data = self.res.json().get('data')
        return rsp_code, ret_result, ret_data

    def get_result_data(self):
        status_code = self.res.status_code
        rsp_code = -1
        ret_result = None
        ret_data = None
        if status_code == 200:
            rsp_code = 0
            ret_result = self.res.json().get('result')
            ret_data = self.res.json()
        return rsp_code, ret_result, ret_data

    def get_download_data(self):
        status_code = self.res.status_code
        rsp_code = -1
        ret_result = None
        ret_data = None
        if status_code == 200:
            rsp_code = 0
            ret_result = 0
            ret_data = []
        return rsp_code, ret_result, ret_data

    def get_rsp_error_data(self):
        status_code = self.res.status_code
        rsp_code = -1
        ret_result = None
        ret_data = None
        if status_code == 200:
            rsp_code = 0
            ret_result = self.res.json().get('error')
            ret_data = self.res.json().get('data')
        return rsp_code, ret_result, ret_data

    def get_net_validity_data(self):
        status_code = self.res.status_code
        rsp_code = -1
        ret_data = None
        if status_code == 200:
            rsp_code = 0
            ret_data = self.res.json().get('data')
        return rsp_code, ret_data

    def get_storage_ip(self):
        res = self.res.json()
        storage_ip = ""
        if not res.get('data'):
            return storage_ip
        for network_data in res.get('data'):
            ip_addr_list = network_data.get('ip_address_list')
            if not ip_addr_list:
                continue
            for ip_addr in ip_addr_list:
                ip_usage = ip_addr.get('ip_usage')
                if not ip_usage:
                    continue
                ip_usage_str = ",".join(ip_usage)
                if 0 > ip_usage_str.find("storage_backend") and 0 > \
                        ip_usage_str.find("storage_frontend"):
                    continue
                storage_ip = ip_addr.get('ip_address')
                return storage_ip
        return storage_ip

    def get_iscsi_result(self):
        res = self.res.json()
        return res.get('successDetail')
