package com.liquidnet.service.base;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Data
public class ErrorMapping {
    private static final Logger log = LoggerFactory.getLogger(ErrorMapping.class);
    private static final Properties errorsProperties;
    static {
        errorsProperties = reload();
    }

    public static Properties reload() {
        Properties errorsProperties = new Properties();
        InputStream in = ErrorMapping.class.getClassLoader().getResourceAsStream("errors.properties");
        try {
            errorsProperties.load(new InputStreamReader(in, StandardCharsets.UTF_8));
            log.info("Load errorsProperties init count:{}", errorsProperties.size());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return errorsProperties;
    }

    public static ErrorMessage get(long code) {
        String value = errorsProperties != null ? errorsProperties.getProperty(code + "") : "-";
        return ErrorMessage.getInstance().setCode(code + "").setMessage(value);
    }

    public static ErrorMessage get(String code) {
        String value = errorsProperties != null ? errorsProperties.getProperty(code) : "-";
        return ErrorMessage.getInstance().setCode(code).setMessage(value);
    }

    public static class ErrorMessage implements Cloneable, Serializable {
        private static final long serialVersionUID = 2208924091512163151L;
        private String code;
        private String message;

        private ErrorMessage() {
        }

        public String getCode() {
            return code;
        }

        public String getMessage() {
            return message;
        }

        private final static ErrorMessage instance = new ErrorMessage();

        public static ErrorMessage getInstance() {
            try {
                return (ErrorMessage) instance.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return new ErrorMessage();
        }

        public ErrorMessage setCode(String code) {
            this.code = code;
            return this;
        }

        public ErrorMessage setMessage(String message) {
            this.message = message;
            return this;
        }
    }
}
