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

import lombok.RequiredArgsConstructor;
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.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.host.service.MirrorService2;
import ru.yandex.webmaster3.storage.mirrors.data.MirrorActionEnum;
import ru.yandex.webmaster3.storage.mirrors.data.MirrorRequest;
import ru.yandex.webmaster3.storage.mirrors.service.MainMirrorService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * @author avhaliullin
 */
@Description("Отклеить зеркало")
@WriteAction
@Category("mirrors")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/mirrors/unstick")
public class UnstickMirrorAction extends AbstractUserVerifiedHostAction<UnstickMirrorRequest, UnstickMirrorResponse> {
    private final MainMirrorService mainMirrorService;
    private final MirrorService2 mirrorService2;

    @Override
    public UnstickMirrorResponse process(UnstickMirrorRequest request) {
        WebmasterHostId oldMainMirror = mirrorService2.getMainMirror(request.getHostId());
        if (oldMainMirror == null) {
            oldMainMirror = request.getHostId();
        }
        if (MirroringActionsUtil.getAvailableAction(request.getHostId(), oldMainMirror) != MirrorActionEnum.UNSTICK) {
            return new UnstickMirrorResponse.UnsupportedAction();
        }

        MirrorRequest currentMirrorRequest = mainMirrorService.getLatestRequest(request.getHostId());
        if (currentMirrorRequest != null) {
            if (!currentMirrorRequest.getState().isTerminal()) {
                return new UnstickMirrorResponse.PreviousTaskNotFinished();
            }
        }

        MirrorRequest newRequest = mainMirrorService.addUnstickRequest(request.getHostId(), oldMainMirror);
        mainMirrorService.scheduleTask(request.getHostId());

        return new UnstickMirrorResponse.NormalResponse(newRequest);
    }
}
