package com.ycwl.basic.facebody;

import com.ycwl.basic.facebody.adapter.AliFaceBodyAdapter;
import com.ycwl.basic.facebody.adapter.BceFaceBodyAdapter;
import com.ycwl.basic.facebody.adapter.IFaceBodyAdapter;
import com.ycwl.basic.facebody.enums.FaceBodyAdapterType;
import com.ycwl.basic.facebody.exceptions.FaceBodyUnsupportedException;
import com.ycwl.basic.storage.exceptions.StorageConfigException;
import com.ycwl.basic.storage.exceptions.StorageUndefinedException;

import java.util.HashMap;
import java.util.Map;

public class FaceBodyFactory {
    public static IFaceBodyAdapter getAdapter(String typeName) {
        FaceBodyAdapterType adapterEnum;
        try {
            adapterEnum = FaceBodyAdapterType.valueOf(typeName);
        } catch (Exception e) {
            throw new FaceBodyUnsupportedException("不支持的Adapter类型");
        }
        return getAdapter(adapterEnum);
    }

    public static IFaceBodyAdapter getAdapter(FaceBodyAdapterType type) {
        return switch (type) {
            case ALI -> new AliFaceBodyAdapter();
            case BCE -> new BceFaceBodyAdapter();
            default -> throw new FaceBodyUnsupportedException("不支持的Adapter类型");
        };
    }


    protected static Map<String, IFaceBodyAdapter> namedAdapter = new HashMap<>();
    protected static IFaceBodyAdapter defaultAdapter = null;

    public static void register(String name, IFaceBodyAdapter adapter) {
        namedAdapter.put(name, adapter);
    }

    public static IFaceBodyAdapter use(String name) {
        IFaceBodyAdapter adapter = namedAdapter.get(name);
        if (adapter == null) {
            throw new StorageUndefinedException("未定义的存储方式："+name);
        }
        return adapter;
    }

    public static IFaceBodyAdapter use() {
        if (defaultAdapter == null) {
            throw new StorageConfigException("未定义默认存储方式");
        }
        return defaultAdapter;
    }

    public static void setDefault(String defaultName) {
        FaceBodyFactory.defaultAdapter = use(defaultName);
    }
}
