package com.ycwl.basic.pay;

import com.ycwl.basic.pay.adapter.CongMingPayAdapter;
import com.ycwl.basic.pay.adapter.IPayAdapter;
import com.ycwl.basic.pay.adapter.WxMpPayAdapter;
import com.ycwl.basic.pay.enums.PayAdapterType;
import com.ycwl.basic.pay.exceptions.PayUndefinedException;
import com.ycwl.basic.pay.exceptions.PayUnsupportedException;

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

public class PayFactory {

    public static IPayAdapter getAdapter(String typeName) {
        PayAdapterType adapterEnum;
        try {
            adapterEnum = PayAdapterType.valueOf(typeName);
        } catch (IllegalArgumentException e) {
            throw new PayUnsupportedException("不支持的Adapter类型");
        }
        return getAdapter(adapterEnum);
    }

    public static IPayAdapter getAdapter(PayAdapterType type) {
        return switch (type) {
            case WX_MP_PAY -> new WxMpPayAdapter();
            case CONG_MING_PAY -> new CongMingPayAdapter();
            default -> throw new PayUnsupportedException("不支持的Adapter类型");
        };
    }

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

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

    public static IPayAdapter use(String name) {
        IPayAdapter adapter = namedAdapter.get(name);
        if (adapter == null) {
            throw new PayUndefinedException("未定义的支付方式："+name);
        }
        return adapter;
    }

    public static IPayAdapter use() {
        if (defaultAdapter == null) {
            throw new PayUndefinedException("未定义默认的支付方式");
        }
        return defaultAdapter;
    }

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