package ru.yandex.wmtools.common.service;

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.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;

/**
 * User: baton
 * Date: May 7, 2007
 * Time: 1:59:48 PM
 */
public class ViewerUserIdService implements IService, IViewerUserIdService {
    private static final Logger log = LoggerFactory.getLogger(ViewerUserIdService.class);

    private ISupportService supportService;
    private IUserInfoService userInfoService;

    @Override
    public long getAndCheckUserId(final ServRequest req, ServResponse res) throws UserException, InternalException {
        Long userId = checkUserId(req.getUserId());
        assureUserIsInUsersList(req.getUserId());
        checkUserIsNotBlockedAndAcceptedLicence(userId);
        return userId;
    }

    @Override
    public long checkUserId(final Long userId) throws UserException {
        if (userId == null) {
            throw new UserException(UserProblem.USER_NOT_SIGNED_IN, "User not signed in!");
        }
        return userId;
    }

    @Override
    public void assureUserIsInUsersList(long userId) throws InternalException, UserException {
        log.debug("assureUserIsInUsersList: start");
        if (!supportService.isKnownUser(userId)) {
            log.debug("assureUserIsInUsersList: try add user " + userId);
            userInfoService.createNewUser(userId);
        }
    }

    @Override
    public void checkUserIsNotBlockedAndAcceptedLicence(long userId) throws UserException, InternalException {
        if (supportService.isBlockedUser(userId)) {
            throw new UserException(UserProblem.USER_IS_BLOCKED, "User " + userId + " is blocked.");
        }
        if (supportService.isUserHaventAcceptedLicence(userId)) {
            throw new UserException(UserProblem.USER_HAVENT_ACCEPTED_LICENCE, "User " + userId + " haven't accepted licence.");
        }
    }

    @Required
    public void setSupportService(ISupportService supportService) {
        this.supportService = supportService;
    }

    @Required
    public void setUserInfoService(IUserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }
}
