package com.ecep.contract.ds.converter;

import java.util.List;
import java.util.function.Function;

import org.hibernate.Hibernate;

import com.ecep.contract.model.BasedEntity;
import com.ecep.contract.model.NamedEntity;


public class EntityStringConverter<T> {

    private Function<T, T> initialized;
    private Function<String, T> fromString;
    private Function<T, String> formater;
    private Function<String, List<T>> suggestion;

    public String toString(T cc) {
        if (cc == null) {
            return "-";
        }
        cc = prefixObject(cc);
        return toPrettyString(cc);
    }

    public T prefixObject(T cc) {
        if (cc == null) {
            return null;
        }
        if (initialized != null && !Hibernate.isInitialized(cc)) {
            cc = initialized.apply(cc);
        }
        return cc;
    }

    public String toPrettyString(T cc) {
        if (formater != null) {
            return formater.apply(cc);
        }
        if (cc == null) {
            return null;
        }
        if (cc instanceof BasedEntity e) {
            return e.toPrettyString();
        }
        if (cc instanceof NamedEntity e) {
            return e.getName();
        }
        return cc.toString();
    }

    public T fromString(String string) {
        if (fromString == null) {
            return null;
        }
        return fromString.apply(string);
    }

    public void setFromString(Function<String, T> fromString) {
        this.fromString = fromString;
    }

    public void setInitialized(Function<T, T> initialized) {
        this.initialized = initialized;
    }

    public void setFormater(Function<T, String> formater) {
        this.formater = formater;
    }

    /**
     * 设置自动补全的数据提供方法
     *
     * @param suggestion 数据提供方法
     */
    public void setSuggestion(Function<String, List<T>> suggestion) {
        this.suggestion = suggestion;
    }
}
