package enea.lecservice.models.dto;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.text.StringEscapeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
public class ServiceResponse<T> {
    private boolean success;
    private List<String> messages = new ArrayList();
    private T result;


    public ServiceResponse() {}

    public ServiceResponse(boolean success, List<String> messages, T result) {
        this.success = success;
        this.messages = messages == null ? null : messages.stream().map(StringEscapeUtils::escapeHtml4).collect(Collectors.toList());
        this.result = result;
    }

    public static <T> ServiceResponse<T> Success(T result) {
        return new ServiceResponse(true, new ArrayList(), result);
    }

    public static <T> ServiceResponse<T> Success(T result, Date updated) {
        return new ServiceResponse(true, new ArrayList(), new Object() {
            public T data = result;

            public Date lastUpdate = updated != null ? updated : new Date();
        });
    }

    public static <T> ServiceResponse<T> Error(Throwable e) {
        List<String> messages = new ArrayList<>();
        messages.add(e.getMessage() == null ? e.toString() : e.getMessage());
        String rootCause = ExceptionUtils.getRootCauseMessage(e);
        messages.add(rootCause);
        return new ServiceResponse<>(false, messages, null);
    }

    public static ServiceResponse Success() {
        return Success(null);
    }

    public static ServiceResponse Error(List<String> errors) {
        return new ServiceResponse(false, errors, null);
    }

    public static <T> ServiceResponse<T>  Error(String error) {
        var errors = new ArrayList<String>();
        errors.add(error);
        return new ServiceResponse<T>(false, errors, null);
    }

    public static <T> ServiceResponse<T> Error(String error, T result) {
        var errors = new ArrayList<String>();
        errors.add(error);
        return new ServiceResponse(false, errors, result);
    }

    /*public static ServiceResponse Error(Exception e) {
        List errors = new ArrayList();
        errors.add(e.getMessage() == null ? e.toString() : e.getMessage());
        return new ServiceResponse(false, errors, null);
    }*/

    public static <T> ServiceResponse<T> Error() {
        return Error(new ArrayList<String>());
    }

    public void addMessage(String message) {
        if (messages == null) {
            this.messages = new ArrayList<>();
        }

        this.messages.add(message);
    }

    /*public String toJSON() {
        return JacksonUtils.toJson(this);
    }*/

    public String getFirstMessage() {
        if (this.messages != null && this.messages.size() > 0)
            return this.messages.get(0);

        return null;
    }
}
