package ru.yandex.wmtools.common.service;

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.util.AuthorizationInfoWrapper;

/**
 * User: baton
 * Date: May 7, 2007
 * Time: 1:59:48 PM
 */
public class VirtualLoginUserIdService implements IService, IUserIdService {
    public static final String VIRTUAL_USER_ID_COOKIE_NAME = "VirtualUserId";

    private IViewerUserIdService viewerUserIdService;
    private SupportUserIdService supportUserIdService;
    private IUserInfoService userInfoService;

    @Override
    public long getAndCheckUserId(final ServRequest req, ServResponse res) throws InternalException, UserException {
        long realUserId = viewerUserIdService.getAndCheckUserId(req, res);
        long virtualUserId = realUserId;
        String virtualUserIdString = req.getCookie(VIRTUAL_USER_ID_COOKIE_NAME);
        if (virtualUserIdString != null) {
            // using virtual id!
            try {
                Long virtualUserIdCandidate = Long.parseLong(virtualUserIdString);
                supportUserIdService.getAndCheckUserId(req, res);

                // rights confirmed.
                virtualUserId = viewerUserIdService.checkUserId(virtualUserIdCandidate);

                res.addData(new AuthorizationInfoWrapper(userInfoService.getUserInfo(realUserId), userInfoService.getUserInfo(virtualUserId)));
            } catch (RuntimeException e) {
                // rights not confirmed.
            } catch (UserException e) {
                // rights not confirmed.
            }
        }

        return virtualUserId;
    }

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

    @Required
    public void setSupportUserIdService(SupportUserIdService supportUserIdService) {
        this.supportUserIdService = supportUserIdService;
    }

    @Required
    public void setViewerUserIdService(IViewerUserIdService viewerUserIdService) {
        this.viewerUserIdService = viewerUserIdService;
    }
}
