package ru.yandex.webmaster3.worker.memorandum;

import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.yandex.webmaster3.storage.util.yt.YtPath;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * @author avhaliullin
 */
public class MemorandumYTUtils {
    private static final Logger log = LoggerFactory.getLogger(MemorandumYTUtils.class);

    public static NavigableMap<Instant, Map<MemorandumYtTableType, YtPath>> parseMemorandumTableNames(List<YtPath> tables) {
        TreeMap<Instant, Map<MemorandumYtTableType, YtPath>> result = new TreeMap<>();
        for (YtPath table : tables) {
            String name = table.getName();
            for (MemorandumYtTableType tableType : MemorandumYtTableType.values()) {
                if (name.endsWith(tableType.getNameSuffix())) {
                    try {
                        long timeMs = Long.parseLong(name.substring(0, name.length() - tableType.getNameSuffix().length()));
                        Instant date = new Instant(timeMs);
                        result.computeIfAbsent(date, ign -> new EnumMap<>(MemorandumYtTableType.class))
                                .put(tableType, table);
                    } catch (NumberFormatException e) {
                        log.warn("Skipping bad table " + table);
                    }
                }
            }
        }
        return result;
    }

    public static String makeTableName(Instant updateDate, MemorandumYtTableType tableType) {
        return String.valueOf(updateDate.getMillis()) + tableType.getNameSuffix();
    }
}
