import re


def volume_convert_yaml_to_json(yaml_conf, version: str):
    """
    Convert yaml configuration to json used to create docker volume.
    Return array of dict, each dict is used in dcli.create_volume(...)
    :param yaml_conf: yaml configuration
    :param version: yaml version (support 2.x/3.x)
    """
    volume_conf_list = []
    # handle version 2
    #if re.match('^2\.(\d*)$', version):
    #    print("Convert volume yaml of version 2.x")
    # handle version 3
    if re.match('^3\.(\d*)$', version):
        for tup in yaml_conf.items():
            volume_conf = {'name': tup[0], 'driver_opts': {}, 'labels': {}}
            if not tup[1]:
                volume_conf['driver'] = 'local'

            if type(tup[1]) is dict:
                # check external
                try:
                    volume_conf['external'] = tup[1]['external']
                except KeyError:
                    pass

                # check driver
                try:
                    volume_conf['driver'] = tup[1]['driver']
                except KeyError:
                    volume_conf['driver'] = 'local'

                # check driver_opts
                try:
                    for dr_tup in tup[1]['driver_opts'].items():
                        volume_conf['driver_opts'][dr_tup[0]] = dr_tup[1]
                except KeyError:
                    pass

                # check labels
                try:
                    for l_tup in tup[1]['labels'].items():
                        volume_conf['labels'][l_tup[0]] = l_tup[1]
                except KeyError:
                    pass

            volume_conf_list.append(volume_conf)
        return volume_conf_list

    return {}