package ru.yandex.webmaster3.viewer.http.filter;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.autodoc.common.doc.params.ParamDescriptor;
import ru.yandex.webmaster3.core.data.UserAddedHost;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.core.http.RequestFilter;
import ru.yandex.webmaster3.core.http.filter.HostIsAddedByUserFilterResponse;
import ru.yandex.webmaster3.core.http.request.AddedHostIdAware;
import ru.yandex.webmaster3.core.http.request.RequestContext;
import ru.yandex.webmaster3.core.http.request.WebmasterHostIdConverter;
import ru.yandex.webmaster3.storage.user.UserUnverifiedHost;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;

/**
 * @author aherman
 */
public class HostIsAddedByUserFilter implements RequestFilter<AddedHostIdAware, HostIsAddedByUserFilterResponse> {
    private UserHostsService userHostsService;

    @Override
    public HostIsAddedByUserFilterResponse beforeRequest(RequestContext ctx, AddedHostIdAware req) {
        WebmasterHostId hostId = req.getHostId();
        WebmasterUser user = req.getWebmasterUser();
        UserAddedHost userAddedHost;
        UserVerifiedHost userVerifiedHost = userHostsService.getVerifiedHost(user, hostId);
        if (userVerifiedHost == null) {
            UserUnverifiedHost unverifiedHost = userHostsService.getUnverifiedHost(user, hostId);
            if (unverifiedHost == null) {
                return new HostIsAddedByUserFilterResponse.HostNotAdded(this.getClass(), hostId);
            } else {
                userAddedHost = new UserAddedHost(hostId, unverifiedHost.getVerificationUin(), false);
            }
        } else {
            userAddedHost = new UserAddedHost(hostId, userVerifiedHost.getVerificationUin(), true);
        }
        req.setUserAddedHost(userAddedHost);
        return null;
    }

    @Override
    public ParamDescriptor clarifyParameter(ParamDescriptor param) {
        if (param.getName().equals("hostId")) {
            return new ParamDescriptor(param.getName(), true, WebmasterHostIdConverter.PARAM_TYPE, null,
                    "добавленный пользователем хост", param.getExtraInfos());
        } else {
            return param;
        }
    }

    @Required
    public void setUserHostsService(UserHostsService userHostsService) {
        this.userHostsService = userHostsService;
    }

}
