package ru.yandex.webmaster3.worker.http.abt;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.WebmasterException;
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.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.storage.abt.dao.AbtHostExperimentYDao;
import ru.yandex.webmaster3.storage.abt.dao.AbtUserExperimentYDao;
import ru.yandex.webmaster3.storage.abt.hash.AbtHashExperimentYDao;


/**
 * @author kravchenko99
 * @date 9/15/20
 */

@Slf4j
@WriteAction
@Component("/experiment/clean/byName")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CleanExperimentByNameAction extends Action<CleanExperimentByNameAction.Req, CleanExperimentByNameAction.Res> {
    private final AbtHostExperimentYDao abtHostExperimentYDao;
    private final AbtUserExperimentYDao abtUserExperimentYDao;
    private final AbtHashExperimentYDao abtHashExperimentYDao;

    @Override
    public Res process(Req request) throws WebmasterException {
        String expName = request.getExperiment();
        String expGroup = request.getGroup();
        abtHostExperimentYDao.forEach(pair -> {
            if (pair.getValue().getExperiment().equals(expName) && pair.getValue().getGroup().equals(expGroup)) {
                log.info("Removing record with exp {} for host {}", pair.getRight().getExperiment(), pair.getLeft());
                abtHostExperimentYDao.delete(pair.getLeft(), pair.getRight());
            }
        });
        abtUserExperimentYDao.forEach(pair -> {
            if (!pair.getValue().getExperiment().equals(expName) && pair.getValue().getGroup().equals(expGroup)) {
                log.info("Removing record with exp {} for user {}", pair.getRight().getExperiment(), pair.getLeft());
                abtUserExperimentYDao.delete(pair.getLeft(), pair.getRight());
            }
        });
        abtHashExperimentYDao.getRecords().forEach(record -> {
            if (record.getExperiment().equals(expName) && record.getGroup().equals(expGroup)) {
                log.info("Removing hash exp {}", record.getExperiment());
                abtHashExperimentYDao.delete(record);
            }
        });
        return new Res();
    }

    @Getter
    @Setter(onMethod_ = @RequestQueryProperty(required = true))
    public static class Req implements ActionRequest {
        String experiment;
        String group;
    }


    public static class Res implements ActionResponse.NormalResponse {

    }
}
