package ru.yandex.wmconsole.data.wrappers;

import java.text.NumberFormat;

import ru.yandex.wmconsole.data.ServerResponseInfo;
import ru.yandex.wmtools.common.util.XmlDataWrapper;

/**
 * User: azakharov
 * Date: 14.12.12
 * Time: 19:14
 */
public class ServerResponseInfoWrapper extends XmlDataWrapper<ServerResponseInfo> {

    private static final String TAG_STATUS = "status";
    private static final String TAG_STATUS_NAME = "status-name";
    private static final String TAG_TIME = "time";
    private static final String TAG_IP = "ip";
    private static final String TAG_LOCATION = "location";
    private static final String TAG_IS_TEXT = "is-text";
    private static final String TAG_ENCODING = "encoding";
    private static final String TAG_SIZE = "size";
    private static final String TAG_BODY = "body";
    private static final String TAG_YANDEX_HTTPCODE = "yandex-http-code";
    private static final String TAG_HEADERS = "headers";
    private static final String TAG_HEADER = "header";
    private static final String ATTRIBUTE_NAME = "name";
    private static final String ATTRIBUTE_VALUE = "value";


    public ServerResponseInfoWrapper(ServerResponseInfo data) {
        super(data);
    }

    @Override
    protected void doToXml(StringBuilder result) {
        putIntegerTag(result, TAG_STATUS, data.getHttpCode());
        putTag(result,TAG_STATUS_NAME , data.getHttpCodeName());
        putLongTag(result, TAG_TIME, data.getResponseTime());
        putTag(result, TAG_IP, data.getIp());
        putTag(result, TAG_LOCATION, data.getLocation());
        putBooleanTag(result, TAG_IS_TEXT, data.isText());
        if (data.isText()) {
            putTag(result, TAG_ENCODING, data.getEncoding());
        }
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        putTag(result, TAG_SIZE, format.format(data.getSize()));
        if (data.getBody() != null) {
            StringWithControlSymbolsWrapper wrapper = new StringWithControlSymbolsWrapper(data.getBody(), TAG_BODY);
            wrapper.toXml(result);
        }
        putIntegerTag(result, TAG_YANDEX_HTTPCODE, data.getYandexHttpCode());

        putOpenTag(result, TAG_HEADERS);
        for (String name : data.getHeaders().keySet()) {
            for (String value : data.getHeaders().get(name)) {
                putSimpleTag(result, TAG_HEADER, ATTRIBUTE_NAME, name, ATTRIBUTE_VALUE, value);
            }
        }
        putCloseTag(result, TAG_HEADERS);
    }
}

