package ru.yandex.qe.logging.security;

import java.util.ArrayList;
import java.util.List;

/**
 * Established by terry
 * on 05.02.14.
 */
public class CookieSecurityGuard implements PrivateHeaderSecurityGuard {

    @Override
    public List<String> secure(String headerName, List<String> headerValues) {
        if (headerName.equalsIgnoreCase("Cookie")) {
            final List<String> securedValues = new ArrayList<>(headerValues.size());
            for (String headerValue : headerValues) {
                securedValues.add(secureValue(headerValue));
            }
            return securedValues;
        }
        return headerValues;
    }

    @Override
    public String secure(String headerName, String headerValue) {
        if (headerName.equalsIgnoreCase("Cookie")) {
            return secureValue(headerValue);
        }
        return headerValue;
    }

    private String secureValue(String headerValue) {
        final String[] parts = headerValue.split(";");
        StringBuilder builder = new StringBuilder();
        for (final String part: parts) {
            if (builder.length() > 0) {
                builder.append(";");
            }
            final int nameSeparator = part.indexOf("=");
            if (nameSeparator < 0) {
                builder.append(part);
            } else {
                builder.append(part.substring(0, nameSeparator+1)).append("***");
            }
        }
        return builder.toString();
    }
}