package ru.yandex.webmaster3.internal.user.takeout;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.user.UserTakeoutRequest;
import ru.yandex.webmaster3.storage.user.service.UserTakeoutService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author leonidrom
 *
 * Ручку нужно явно делать доступной. Подробнее см. Main.java
 */
@Slf4j
@WriteAction
@Description("Получает результаты для созданного ранее запроса на выгрузку пользовательских данных")
public class UserTakeoutGetAction extends InternalAction<UserTakeoutGetRequest, UserTakeoutGetResponse> {
    private static final String USER_TAKEOUT_DATA_TOP_FIELD = "webmaster.json";

    private final UserTakeoutService userTakeoutService;

    @Autowired
    public UserTakeoutGetAction(UserTakeoutService userTakeoutService) {
        super(InternalGrant.USER_TAKEOUT);
        this.userTakeoutService = userTakeoutService;
    }

    @Override
    public UserTakeoutGetResponse process(UserTakeoutGetRequest request) throws WebmasterException {
        UserTakeoutRequest takeoutRequest = userTakeoutService.getRequest(request.getJobId());
        switch (takeoutRequest.getStatus()) {
            case DONE:
                String takeoutData = takeoutRequest.getData();
                if (takeoutData == null) {
                    return new UserTakeoutGetResponse.NoUserDataResponse();
                } else {
                    Map<String, String> resultMap = new HashMap<>();
                    resultMap.put(USER_TAKEOUT_DATA_TOP_FIELD, takeoutData);
                    return new UserTakeoutGetResponse.NormalResponse(resultMap);
                }

            case IN_PROGRESS:
                return new UserTakeoutGetResponse.RequestPendingResponse();

            default:
                String msg = "Unknown status " + takeoutRequest.getStatus();
                throw new WebmasterException(msg, new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(), msg), null);
        }
    }

}
