# -*- coding: utf-8 -*-
# Copyright: 2016, Ableton AG, Berlin. All rights reserved.
from abl.util import LockFileObtainException


def is_info_file(f):
    return "+info" in f.splitext()[1]


def filter_info_files(files):
    for f in files:
        if is_info_file(f):
            yield f


def pivot_selector(name, select_processed=False):
    return name.endswith(".log") or (select_processed and name.endswith("log+processed"))


def pivot_lockfile(pivot):
    return pivot.directory() / (pivot.splitext()[0] + ".log.lock")


def other_logs(f):
    dir_ = f.dirname()
    base = f.splitext()[0]
    for candidate in dir_.glob(base + ".*"):
        ext = candidate.splitext()[1]
        if ext not in (".lock", ".log"):
            yield ext[1:], candidate


def pivot_group(pivot):
    yield pivot
    dir_ = pivot.dirname()
    base = pivot.splitext()[0]
    for candidate in dir_.glob(base + ".*"):
        ext = candidate.splitext()[1]
        if ext not in (".lock", ".log", ".log+processed"):
            yield candidate


def sorted_pivots_most_recent_first(base, select_processed=False):
    names = (name for name in base.listdir() if pivot_selector(name, select_processed))
    return sorted((base / name for name in names), key=lambda f: f.mtime(), reverse=True)


def group_files_by_pivot_most_recent_first(base, select_processed=False):
    for pivot in sorted_pivots_most_recent_first(base, select_processed=select_processed):
        try:
            with pivot_lockfile(pivot).lock(fail_on_lock=True, cleanup=True):
                yield pivot_group(pivot)
        except LockFileObtainException:
            pass


def filter_out_info_files(group):
    for log in group:
        if not is_info_file(log):
            yield log


def mark_as_processed(pivot):
    processed_file = pivot.directory() / (pivot.splitext()[0] + ".log+processed")
    pivot.move(processed_file)
    return processed_file
