package com.eactive.ext.kjb.eai;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

@Slf4j
public class EaiBatchMessage {
    @Getter
    private String interfaceId = "";

    @Getter
    private String baseDate = "";

    @Getter
    private String count = "";

    /**
     * 요청시 사용 안함, 응답시 1: 성공, 2: 실패
     */
    @Getter
    private String resultCode = "";

    @Getter
    private String filename = "";


    private String rawMessage = "";

    private boolean isReadOnly = false;

    private String charset;


    private EaiBatchMessage() {}


    public static EaiBatchMessage createRequest(String interfaceId, String filename, String charset) {
        EaiBatchMessage message = new EaiBatchMessage();
        message.interfaceId = interfaceId;
        message.filename = filename;
        message.charset = charset;

        return message;
    }

    public static EaiBatchMessage fromResponse(String rawMessage) {
        EaiBatchMessage message = new EaiBatchMessage();
        message.rawMessage = rawMessage;
        message.isReadOnly = true;

        if (rawMessage.length() >= 40) {
            message.interfaceId = rawMessage.substring(0, 19).trim();
            message.baseDate = rawMessage.substring(19, 27).trim();
            message.count = rawMessage.substring(27, 37).trim();
            message.resultCode = rawMessage.substring(37, 38).trim();
            // filename 은 @@가 발견되면 이전 까지 trim / 발견되지 않으면 나머지 전체 그리고 trim
            int endIdx = rawMessage.indexOf("@@", 38);
            if (endIdx == -1) {
                message.filename = rawMessage.substring(38).trim();
            } else {
                message.filename = rawMessage.substring(38, endIdx).trim();
            }
        }

        if (StringUtils.isEmpty(message.interfaceId)) {
            log.error("Invalid EAI Batch response message: interfaceId is empty. rawMessage={}", rawMessage);
            throw new IllegalArgumentException("Invalid EAI Batch response message: interfaceId is empty");
        }

        return message;
    }


    @Override
    public String toString() {
        if (isReadOnly) {
            return rawMessage;
        } else {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            try {
                // 인터페이스ID (19)
                buffer.put(fixedString(interfaceId, 19));
                // 기준일자 (8)
                buffer.put(fixedString(baseDate, 8));
                // 건수 (10)
                buffer.put(fixedString(count, 10));
                // 결과코드 (1)
                buffer.put(fixedString(resultCode, 1));
                // 파일명 (100)
                buffer.put(fixedString(filename, 100));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

            // 종료 구분자 (2)
            buffer.put("@@".getBytes());


            return new String(buffer.array()).trim();
        }
    }

    private byte[] fixedString(String str, int length) throws UnsupportedEncodingException {
        if (str == null) {
            str = "";
        }
        byte[] strBytes = str.getBytes(this.charset);
        byte[] result = new byte[length];

        int copyLength = Math.min(strBytes.length, length);
        System.arraycopy(strBytes, 0, result, 0, copyLength);

        for (int i = copyLength; i < length; i++) {
            result[i] = ' ';
        }

        return result;
    }
}
