package ru.yandex.webmaster3.storage.searchurl.history;

import org.joda.time.Instant;
import ru.yandex.webmaster3.core.searchbase.SearchBaseUpdateInfo;
import ru.yandex.webmaster3.core.sitestructure.DoubleSourcedSiteStructure;
import ru.yandex.webmaster3.core.sitestructure.NewSiteStructure;

import java.util.Comparator;
import java.util.List;

/**
 * @author avhaliullin
 */
public class SearchUrlStructuresUtil {
    public static final Comparator<DoubleSourcedSiteStructure> STRUCTURES_COMPARATOR = Comparator
            .comparing(DoubleSourcedSiteStructure::getRealDataCollectionDate)
            .thenComparing(DoubleSourcedSiteStructure::getCreateDate);


    public static NewSiteStructure findBestStructureForUpdate(SearchBaseUpdateInfo updateInfo, List<DoubleSourcedSiteStructure> sortedStructures) {
        Instant switchDate = updateInfo.getBaseSwitchDate();
        NewSiteStructure bestStructure = null;
        for (DoubleSourcedSiteStructure structure : sortedStructures) {
            if (bestStructure != null && (structure.getCreateDate().isAfter(switchDate) && !isWMCSupport1230(updateInfo))) {
                // Пошли структуры после переключения, а подходящую мы уже нашли
                break;
            }
            if (updateInfo.getBaseCollectionDate().equals(structure.getCurBaseDate())) {
                bestStructure = structure.getCurStructure();
            } else if (updateInfo.getBaseCollectionDate().equals(structure.getNextBaseDate())) {
                bestStructure = structure.getNextBaseStructure();
            }
        }
        return bestStructure;
    }

    private static boolean isWMCSupport1230(SearchBaseUpdateInfo updateInfo) {
        return updateInfo.getBaseSwitchDate().equals(WMCSUPPORT_1230_BAD_BASE);
    }

    private static final Instant WMCSUPPORT_1230_BAD_BASE = new Instant(1489270801438L);
}
