# -*- coding: utf-8 -*-
import json
import traceback
import utils.common.log as logger
from utils.common.exception import HCCIException
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()

    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')

        except HCCIException as e:
            logger.error('Update distributed storage directory configuration failed:{}'.format(e))
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error('Update distributed storage directory configuration failed:{}'.format(e))
            logger.error(traceback.format_exc())
            raise HCCIException(621014, str(e))
        finally:
            logger.info('procedure end.')

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

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

    def _check_update_result(self, 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.')
