package ru.yandex.wmconsole.servantlet;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostInfo;
import ru.yandex.wmconsole.data.info.ShortHostInfo;
import ru.yandex.wmconsole.data.wrappers.HostInfoWidgetWrapper;
import ru.yandex.wmconsole.service.error.WMCUserProblem;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class HostInfoWidgetServantlet extends WMCAuthorizedHostOperationServantlet {
    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        Long hostId = null;
        String hostIdParam = req.getParam("host");
        if (!StringUtils.isEmpty(hostIdParam)) {
            hostId = Long.parseLong(hostIdParam);
        }

        if (hostId == null || hostId == 0) {
            List<ShortHostInfo> usersHosts = getHostInfoService().getShortHostList(userId);
            boolean found = false;
            for (ShortHostInfo hostInfo : usersHosts) {
                if (hostInfo.getVerificationState().isVerified()) {
                    hostId = hostInfo.getId();
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new UserException(WMCUserProblem.NO_VERIFIED_HOSTS, "No verified hosts found for user");
            }
        }

        BriefHostInfo briefHostInfo = getHostInfoService().getMainMirrorBriefHostInfoByIdOrName(hostId.toString());
        if (briefHostInfo == null || !getVerifyService().isHostVerifiedByUser(briefHostInfo.getId(), userId)) {
            throw new UserException(WMCUserProblem.HOST_NOT_VERIFIED_BY_USER, "Host is not verified by specified user");
        }

        HostInfo hostInfo = getHostInfoService().getHostInfo(userId, briefHostInfo);

        res.addData(new HostInfoWidgetWrapper(hostInfo));
    }
}
