package ru.yandex.wmconsole.servantlet.internal;

import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.data.wrappers.StringWrapper;
import ru.yandex.wmconsole.service.VerifyViewerService;
import ru.yandex.wmtools.common.data.wrappers.SimpleWrapper;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.servantlet.AbstractServantlet;
import ru.yandex.wmtools.common.util.URLUtil;

/**
 * This servantlet shows if specified host has been added to our service.
 *
 * @author ailyin
 */
public class CheckRegistrationServantlet extends AbstractServantlet {
    private static final Logger log = LoggerFactory.getLogger(CheckRegistrationServantlet.class);

    private static final String PARAM_URL = "url";

    private VerifyViewerService verifyService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res) throws UserException, InternalException {
        log.debug("CheckRegistration: Started");

        String urlString = getRequiredStringParam(req, PARAM_URL);
        try {
            final URL url = prepareUrl(urlString, true);
            final String hostName = URLUtil.getHostName(url, false);
            res.addData(new SimpleWrapper<Boolean>(verifyService.isRegistered(hostName), "registered"));
        } catch (UserException e) {
            res.addData(new StringWrapper("INVALID_URL", "error"));
        }

        log.debug("CheckRegistration: Finished");
    }

    @Required
    public void setVerifyService(VerifyViewerService verifyService) {
        this.verifyService = verifyService;
    }
}
