package ru.yandex.wmconsole.viewer.mac.servantlet;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.Servantlet;
import ru.yandex.common.framework.http.HttpServRequest;
import ru.yandex.common.framework.http.HttpServResponse;
import ru.yandex.wmconsole.viewer.mac.MacService;

/**
 * @author aherman
 */
public class CheckMacServantlet implements Servantlet<HttpServRequest, HttpServResponse> {
    private static final Logger log = LoggerFactory.getLogger(CheckMacServantlet.class);

    private MacService macService;

    @Override
    public void process(HttpServRequest req, HttpServResponse res) {
        String message = req.getParam(CreateMacServantlet.MESSAGE_PARAM, true);
        if (StringUtils.isEmpty(message)) {
            res.addData(new CreateMacServantlet.ErrorResponse(CreateMacServantlet.ErrorType.PARAMETER_MISSING,
                    "Parameter: " + CreateMacServantlet.MESSAGE_PARAM));
            return;
        }

        String mac = req.getParam(CreateMacServantlet.MAC_PARAM, null);
        if (StringUtils.isEmpty(mac)) {
            res.addData(new CreateMacServantlet.ErrorResponse(CreateMacServantlet.ErrorType.PARAMETER_MISSING,
                    "Parameter: " + CreateMacServantlet.MAC_PARAM));
            return;
        }

        byte[] messageBytes;
        try {
            messageBytes = message.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("Unable to convert message: " + message, e);
            res.setHttpStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            res.addData(new CreateMacServantlet.ErrorResponse(CreateMacServantlet.ErrorType.INTERNAL_ERROR,
                    e.getMessage()));
            return;
        }

        try {
            boolean macIsValid = macService.validateMac(messageBytes, mac);
            res.addData(new CreateMacServantlet.NormalResponse(message, mac, macIsValid));
        } catch (InvalidKeyException e) {
            log.error("Unable to check mac: message=" + message + ", mac=" + mac, e);
            res.setHttpStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            res.addData(new CreateMacServantlet.ErrorResponse(CreateMacServantlet.ErrorType.INTERNAL_ERROR,
                    e.getMessage()));
        }
    }

    @Required
    public void setMacService(MacService macService) {
        this.macService = macService;
    }
}
