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

import java.util.List;

import com.google.common.base.Strings;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.blackbox.GetEmailsType;
import ru.yandex.webmaster3.core.blackbox.UserEmailInfo;
import ru.yandex.webmaster3.core.blackbox.UserWithLogin;
import ru.yandex.webmaster3.core.blackbox.service.BlackboxUsersService;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.user.UserPersonalInfo;
import ru.yandex.webmaster3.storage.user.service.UserPersonalInfoService;
import ru.yandex.webmaster3.viewer.http.user.FindUserAction.Request;
import ru.yandex.webmaster3.viewer.http.user.FindUserAction.Response;

/**
 * Created by Oleg Bazdyrev on 21/10/2021.
 */
@ReadAction
@Category("internal")
@Component("/user/find")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FindUserAction extends Action<Request, Response> {

    private final BlackboxUsersService blackboxExternalYandexUsersService;
    private final UserPersonalInfoService userPersonalInfoService;

    @Override
    public Response process(Request request) throws WebmasterException {
        UserWithLogin userLogin = null;
        if (request.uid != null) {
            userLogin = blackboxExternalYandexUsersService.getUserById(request.uid);
        } else if (!Strings.isNullOrEmpty(request.login)) {
            userLogin = blackboxExternalYandexUsersService.getUserByLogin(request.login);
        }
        if (userLogin == null) {
            return new Response(null, null);
        }
        UserPersonalInfo personalInfo = userPersonalInfoService.getUserPersonalInfo(userLogin.getUserId());
        List<UserEmailInfo> emailInfos = blackboxExternalYandexUsersService.getUserEmails(userLogin.getUserId(), GetEmailsType.ALL);
        return new Response(personalInfo, emailInfos);
    }

    public static final class Request implements ActionRequest {
        @Setter(onMethod_ = @RequestQueryProperty)
        Long uid;
        @Setter(onMethod_ = @RequestQueryProperty)
        String login;
    }

    @Value
    public static class Response implements ActionResponse.NormalResponse {
        UserPersonalInfo personalInfo;
        List<UserEmailInfo> emailInfos;
    }
}
