import pymel.core as pm
import os
import re
import os
import six

# todo make configs

PROJECT_FS_SCHEMA = None
if os.environ.get("PROJECT_NAME") and os.environ.get("PROJECT_ROOT_PATH"):
    import wizart.fs_ctrl.fs_schema

    try:
        PROJECT_FS_SCHEMA = wizart.fs_ctrl.fs_schema.ProjectFileSchema(os.environ["PROJECT_NAME"],
                                                                       os.environ["PROJECT_ROOT_PATH"])
        PROJECT_FS_SCHEMA.load_components()
    except Exception as e:
        pm.warning(str(e))

if os.environ.get("WIZART_FREELANCE") == '1':
    FREELANCE = True
else:
    FREELANCE = False


def asset_data_from_ref_new_fs(ref):
    basename = os.path.basename(ref.withCopyNumber())
    match = re.search("(?P<asset_name>\w+).+\{(?P<instance_num>\d+)\}", basename) or re.search("(?P<asset_name>\w+).+",
                                                                                               basename)
    if not match:
        return (None, None, None)

    asset_name = match.groupdict().get('asset_name', None)
    asset_instance = int(match.groupdict().get('instance_num', 0))
    return asset_name, None, asset_instance


def asset_data_from_ref(ref):
    asset_name, asset_version, asset_instance = asset_data_from_ref_old_fs(ref)
    if asset_name is not None:
        return asset_name, asset_version, asset_instance
    else:
        return asset_data_from_ref_new_fs(ref)


def asset_data_from_ref_old_fs(ref):
    basename = os.path.basename(ref.withCopyNumber())
    match = re.search("(?P<asset_name>\w+)_v(?P<asset_version>\d+).+\{(?P<instance_num>\d+)\}", basename) or re.search(
        "(?P<asset_name>\w+)_v(?P<asset_version>\d+).+", basename)
    if not match:
        return (None, None, None)

    asset_name = match.groupdict().get('asset_name', None)
    asset_version = int(match.groupdict().get('asset_version', None))
    asset_instance = int(match.groupdict().get('instance_num', 0))
    return asset_name, asset_version, asset_instance


def find_old_fs(asset_name, asset_path):
    picker_path = os.path.dirname(asset_path) + "/" + asset_name + ".picker"
    return six.ensure_str(picker_path)


def find_new_fs(asset_name, asset_path):
    match = re.findall('(.*{asset})/.*'.format(asset=asset_name), asset_path)
    if match:
        asset_dir = match[0]
        result = os.path.join(asset_dir, 'rig/picker/{asset}.picker').format(asset=asset_name)
        result = result.replace('\\', '/').encode()
        result = six.ensure_str(result)
        return result


def find_picker_new_fs(asset_name, asset_path):
        match = re.search("[wW]:[/_a-zA-Z0-9]+/([a-z]+|v[0-9]+)/", asset_path)
        if match:
            anim_rig_fs_node = PROJECT_FS_SCHEMA.find_node_by_path(asset_path)
            asset_fs_node = anim_rig_fs_node.component_parent_node
            rig_group_fs_node = asset_fs_node.find_child_partial("rig")
            if rig_group_fs_node:
                picker_fs_folder = rig_group_fs_node.find_child_partial("picker")
                if picker_fs_folder:
                    picker_folder = PROJECT_FS_SCHEMA._resolve_node_path(picker_fs_folder.get_fullpath(),
                                                                            dict(asset=asset_name,
                                                                                root=PROJECT_FS_SCHEMA.project_path))
                    return six.ensure_str(os.path.join(picker_folder, "%s.picker" % asset_name))


def find_picker(asset_name, asset_path):
    result = None
    if FREELANCE:
        result = find_new_fs(asset_name, asset_path)
    elif PROJECT_FS_SCHEMA is not None:
        result = find_picker_new_fs(asset_name, asset_path)

    if result:
        return result
    else:
        return find_old_fs(asset_name, asset_path)


def make_asset_info():
    asset_info = dict()
    asset_info["namespace"] = ""
    asset_info["name"] = ""
    asset_info["path"] = ""
    asset_info["picker_path"] = None
    return asset_info


def get_asset_info_from_ref(ref):
    namespace = ref_namespace = ref.refNode.namespace() + ref.namespace
    # filter props for now
    if pm.objExists(namespace + ":character") or pm.objExists(namespace + ":rig"):
        asset_name, _, _ = asset_data_from_ref(ref)
        if asset_name:
            asset_path = ref.path.replace("\\", "/")
            asset_info = make_asset_info()
            asset_info["namespace"] = six.ensure_str(namespace)
            asset_info["name"] = six.ensure_str(asset_name)
            asset_info["path"] = six.ensure_str(asset_path)
            asset_info["picker_path"] = six.ensure_str( find_picker(asset_name, asset_path))
            return asset_info


def get_scene_asset_list():
    """
    Return picker asset-candidates for new picker tab
    """
    result = []
    for ref in pm.listReferences():
        asset_info = get_asset_info_from_ref(ref)
        if asset_info:
            result.append(asset_info)
    return result