package ru.yandex.wmconsole.viewer.api.servantlet.originals;

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.authorization.ApiOAuthPermission;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostInfo;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.error.ClientProblem;
import ru.yandex.wmconsole.servantlet.api.AbstractApiServantlet;
import ru.yandex.wmconsole.viewer.originals.OriginalTextsService;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author aherman
 */
public abstract class ApiBaseOriginalTextsServantlet extends AbstractApiServantlet {
    protected OriginalTextsService originalTextsService;

    private int minimumHostTic = 0;

    @Override
    protected void apiDoProcess(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {
        BriefHostInfo briefHostInfo = getHostInfo(req, false, userId, true, true, res, false, false);
        if (minimumHostTic > 0) {
            HostInfo hostInfo = getHostInfoService().getHostInfo(userId, briefHostInfo);
            if (hostInfo.getTcy() == null || hostInfo.getTcy() < minimumHostTic) {
                throw new ClientException(ClientProblem.NOT_ENOUGH_TIC, "You site have not enough TIC");
            }
        }

        doProcess(req, res, userId, briefHostInfo);
    }

    protected abstract void doProcess(ServRequest req, ServResponse res, long userId, BriefHostInfo briefHostInfo)
            throws ClientException;

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

    @Required
    public void setOriginalTextsService(OriginalTextsService originalTextsService) {
        this.originalTextsService = originalTextsService;
    }

    public void setMinimumHostTic(int minimumHostTic) {
        this.minimumHostTic = minimumHostTic;
    }
}
