# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import json
import utils.common.log as logger
from utils.client.FSPAuthClient import FSPAuthClient
from utils.DBAdapter.DBConnector import BaseOps
from plugins.DistributedStorage.common.base import TestCase


class UpdateDirectoryCfg(TestCase):
    def __init__(self, project_id, pod_id):
        super(UpdateDirectoryCfg, self).__init__(project_id, pod_id)
        self.db = BaseOps()

    @staticmethod
    def _update_hostcfg_item(cps_client):
        param = {'name': 'dfv',
                 'size': '5g'}
        cps_client.do_hostcfg_host_item_update('storage', 'default', 'logical-volume', param)

    @staticmethod
    def _show_hostcfg(cps_client):
        res = cps_client.do_hostcfg_show('storage', 'default')
        resp = json.dumps(res)
        logger.info('Hostcfg info:%s' % resp)
        return res

    @staticmethod
    def _check_update_result(res):
        logical_voulume = res.get('logical-volume')
        dfv_volume = '5g'
        for item in logical_voulume:
            if item.get('name') == 'dfv':
                if item.get('size') != dfv_volume:
                    err_msg = 'Size of the dfv directory in hostcfg [%s] is' \
                              ' not expected size [%s].' % (item.get('size'), dfv_volume)
                    logger.error(err_msg)
                    raise Exception(err_msg)
        logger.info('Size of the dfv directory is expected size.')

    def procedure(self):
        try:
            logger.info('Start update distributed storage directory configuration.')
            cps_client = FSPAuthClient.get_cps_rest_client(self.db, self.project_id, self.pod_id)
            logger.info('Get cps client: %s.' % cps_client)

            logger.info('Show origin hostcfg item')
            self._show_hostcfg(cps_client)

            logger.info('Start to update hostcfg item.')
            self._update_hostcfg_item(cps_client)
            logger.info('Update hostcfg item successful')

            logger.info('Do cps commit')
            cps_client.do_commit()

            logger.info('Show updated hostcfg item')
            res = self._show_hostcfg(cps_client)

            logger.info('Check update result')
            self._check_update_result(res)

            logger.info('Update distributed storage directory configuration finished')
        finally:
            logger.info('procedure end.')
