package ru.yandex.wmconsole.servantlet.api;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.authorization.ApiOAuthPermission;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostInfo;
import ru.yandex.wmconsole.data.info.api.ApiExtendedHostInfo;
import ru.yandex.wmconsole.data.wrappers.api.ApiExtendedHostInfoWrapper;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.error.ClientProblem;
import ru.yandex.wmconsole.viewer.api.ApiExtendedSiteInfo;
import ru.yandex.wmconsole.viewer.api.ApiVersion;
import ru.yandex.wmconsole.viewer.api.wrappers.ApiExtendedSiteInfoWrapper;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author ailyin
 */
public class ApiHostInfoServantlet extends AbstractApiServantlet {
    @Override
    public void apiDoProcess(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {
        String apiVersionStr = req.getParam(ApiVersion.API_VERSION_PARAM, ApiVersion.V1.name());
        ApiVersion apiVersion = ApiVersion.valueOf(apiVersionStr);

        BriefHostInfo briefHostInfo = getHostInfo(req, false, userId, true, false, res, false, false);
        HostInfo hostInfo = getHostInfoService().getHostInfo(userId, briefHostInfo);

        if (apiVersion == ApiVersion.V1 ||
                apiVersion == ApiVersion.V2) {

            if (briefHostInfo.getMainMirrorId() != null) {
                throw new ClientException(ClientProblem.MIRROR_IS_NOT_ALLOWED, "Not main mirror is not allowed");
            }
            ApiExtendedHostInfo info = new ApiExtendedHostInfo(hostInfo.getId(), hostInfo.getName(),
                    hostInfo.getVerificationState(), hostInfo.getVerificationType(), hostInfo.getUrlCount(),
                    hostInfo.isVirused(), hostInfo.getTcy(), hostInfo.getIndexCount(), hostInfo.getHostInfoStatus(),
                    hostInfo.getLastAccess(), hostInfo.getUrlErrors(), hostInfo.getInternalLinksCount(),
                    hostInfo.getLinksCount());

            res.addData(new ApiExtendedHostInfoWrapper(info));

        } else if (apiVersion == ApiVersion.V3) {

            ApiExtendedSiteInfo info = new ApiExtendedSiteInfo(hostInfo.getId(), hostInfo.getName(),
                    hostInfo.getVerificationState(), hostInfo.getVerificationType(), hostInfo.getUrlCount(),
                    hostInfo.isVirused(), hostInfo.getTcy(), hostInfo.getIndexCount(), hostInfo.getHostInfoStatus(),
                    hostInfo.getLastAccess(), briefHostInfo.getMainMirrorId() == null, hostInfo.getUrlErrors(), hostInfo.getInternalLinksCount(),
                    hostInfo.getLinksCount());

            res.addData(new ApiExtendedSiteInfoWrapper(info));

        }
    }

    @Override
    public ApiOAuthPermission getRequiredPermission() {
        return ApiOAuthPermission.COMMON_OPERATIONS;
    }
}
