package ru.yandex.qe.bus.features.log;

import java.util.List;
import java.util.Map;

import org.apache.cxf.message.Message;

/**
 * @author alisovenko 19.07.14
 */
public interface LogInterceptFormatter {
    void formatLine(Message msg, StringBuilder sb, LogFeature logFeature);

    class Info implements LogInterceptFormatter {
        @Override
        public void formatLine(Message message, StringBuilder logBuilder, LogFeature logFeature) {
            if (message.containsKey(Message.ENDPOINT_ADDRESS)) {
                logBuilder.append("address: ").append(message.get(Message.ENDPOINT_ADDRESS)).append("; ");
            }
            if (message.containsKey(Message.REQUEST_URL)) {
                logBuilder.append("url: ").append(message.get(Message.REQUEST_URL));
                if (message.containsKey(Message.QUERY_STRING) && message.get(Message.QUERY_STRING) != null) {
                    logBuilder.append("?").append(message.get(Message.QUERY_STRING));
                }
                logBuilder.append("; ");
            }
            if (message.containsKey(Message.HTTP_REQUEST_METHOD)) {
                logBuilder.append("method: ").append(message.get(Message.HTTP_REQUEST_METHOD)).append("; ");
            }
            if (message.containsKey(Message.RESPONSE_CODE)) {
                logBuilder.append("resp-code: ").append(message.get(Message.RESPONSE_CODE)).append("; ");
            }
            if (message.containsKey(Message.CONTENT_TYPE) && message.get(Message.CONTENT_TYPE) != null) {
                logBuilder.append("content-type: ").append(removeBoundary(message.get(Message.CONTENT_TYPE).toString())).append("; ");
            }
        }

        private String removeBoundary(String contentType) {
            int beginIndex = contentType.indexOf("; boundary=");
            return beginIndex < 0 ? contentType : contentType.substring(0, beginIndex);
        }
    }
    class Trace extends Info {
        @Override
        public void formatLine(Message message, StringBuilder logBuilder, LogFeature logFeature) {
            super.formatLine(message, logBuilder, logFeature);

            if (message.containsKey(Message.ENCODING)) {
                logBuilder.append("encoding: ").append(message.get(Message.ENCODING)).append("; ");
            }
            if (message.containsKey(Message.PROTOCOL_HEADERS)) {
                @SuppressWarnings("unchecked")
                final Map<String, List<String>> headersMap = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
                logBuilder.append("headers: ").append(logFeature.securePrivateData(headersMap)).append("; ");
            }
        }
    }
}
