package ru.yandex.wmconsole.servantlet.api;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.util.db.OrderByClause;
import ru.yandex.wmconsole.authorization.ApiOAuthPermission;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.UrlErrorsWithCodeInfo;
import ru.yandex.wmconsole.data.wrappers.api.ApiErrorInfoWrapper;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.service.ErrorInfoService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

/**
 * @author ailyin
 */
public class ApiErrorInfoServantlet extends AbstractApiServantlet {
    private ErrorInfoService errorInfoService;

    @Override
    public void apiDoProcess(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {

        BriefHostInfo briefHostInfo = getHostInfo(req, false, userId, true, true, res, false, false);
        if (briefHostInfo == null) {
            return;
        }

        //todo (minor) use getErrorGroupsList?
        Collection<UrlErrorsWithCodeInfo> urlErrors = errorInfoService.getOrderedErrorGroupsList(
                userId, briefHostInfo, new OrderByClause((String) null));
        int totalCount = 0;
        for (UrlErrorsWithCodeInfo info : urlErrors) {
            totalCount += info.getCount();
        }

        XmlConvertableCollectionWrapper wrappedUrlErrors = XmlConvertableCollectionWrapper.wrap(
                urlErrors, ApiErrorInfoWrapper.class, "url-errors", "count", Integer.toString(totalCount));
        res.addData(wrappedUrlErrors);
    }

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

    @Required
    public void setErrorInfoService(ErrorInfoService errorInfoService) {
        this.errorInfoService = errorInfoService;
    }
}
