package ru.yandex.webmaster3.viewer.http.turbo.autoparser;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.autoparser.AutoparserToggleState;
import ru.yandex.webmaster3.core.turbo.model.autoparser.TurboAutoparsedHostInfo;
import ru.yandex.webmaster3.storage.cache.DashboardCacheService;
import ru.yandex.webmaster3.storage.cache.DashboardType;
import ru.yandex.webmaster3.storage.turbo.dao.autoparser.TurboAutoparsedYDao;
import ru.yandex.webmaster3.storage.turbo.service.autoparser.TurboAutoparserInfoService;
import ru.yandex.webmaster3.storage.turbo.service.autoparser.TurboAutoparserInfoUtil;
import ru.yandex.webmaster3.storage.turbo.service.settings.TurboSettingsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.turbo.dashboard.GetTurboDashboardInfoAction;

/**
 * Created by ifilippov5 on 19.06.18.
 */
@WriteAction
@Category("turbo")
@Description("Поменять значение галки автопарсера")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SetAutoparserToggleStateAction extends AbstractUserVerifiedHostAction<SetAutoparserToggleStateRequest, SetAutoparserToggleStateResponse> {

    private final DashboardCacheService dashboardCacheService;
    private final TurboAutoparsedYDao turboAutoparsedYDao;
    private final TurboAutoparserInfoService turboAutoparserInfoService;
    private final TurboSettingsService turboSettingsService;

    @Override
    public SetAutoparserToggleStateResponse process(SetAutoparserToggleStateRequest request) {
        String host = TurboAutoparserInfoUtil.canonizeHost(request.getHostId());
        TurboAutoparsedHostInfo info = turboAutoparsedYDao.get(host);
        boolean hasPages = turboAutoparserInfoService.isHostInfoActual(info);
        if (!hasPages) {
            return new SetAutoparserToggleStateResponse.NormalResponse();
        }

        AutoparserToggleState state = AutoparserToggleState.OFF;
        if (request.isChecked()) {
            state = AutoparserToggleState.ON;
        }
        turboAutoparsedYDao.update(host, state);
        turboSettingsService.notifyAboutSettingsChange(host, null, state, null);
        dashboardCacheService.invalidate(request.getHostId(), DashboardType.TURBO,
                GetTurboDashboardInfoAction.SER_VER);

        return new SetAutoparserToggleStateResponse.NormalResponse();
    }

}
