# #!/usr/bin/env python
#
import os

from config import Config
from helpers import (
    fade_point,
    get_audio_segment,
    get_tags,
    leading_silence,
    normalise_track,
    set_track_metadata,
    trailing_silence,
)
from log import log
from models import Tracks


def check_db(session):
    """
    Database consistency check.

    A report is generated if issues are found, but there are no automatic
    corrections made.

    Search for tracks that are in the music directory but not the datebase
    Check all paths in database exist
    """

    db_paths = set([a.path for a in Tracks.get_all(session)])

    os_paths_list = []
    for root, _dirs, files in os.walk(Config.ROOT):
        for f in files:
            path = os.path.join(root, f)
            ext = os.path.splitext(f)[1]
            if ext in [".flac", ".mp3"]:
                os_paths_list.append(path)
    os_paths = set(os_paths_list)

    # Find any files in music directory that are not in database
    files_not_in_db = list(os_paths - db_paths)

    # Find paths in database missing in music directory
    paths_not_found = []
    missing_file_count = 0
    more_files_to_report = False
    for path in list(db_paths - os_paths):
        if missing_file_count >= Config.MAX_MISSING_FILES_TO_REPORT:
            more_files_to_report = True
            break

        missing_file_count += 1

        track = Tracks.get_by_path(session, path)
        if not track:
            # This shouldn't happen as we're looking for paths in
            # database that aren't in filesystem, but just in case...
            log.error(f"update_db: {path} not found in db")
            continue

        paths_not_found.append(track)

    # Output messages (so if running via cron, these will get sent to
    # user)
    if files_not_in_db:
        print("Files in music directory but not in database")
        print("--------------------------------------------")
        print("\n".join(files_not_in_db))
        print("\n")
    if paths_not_found:
        print("Invalid paths in database")
        print("-------------------------")
        for t in paths_not_found:
            print(f"""
                Track ID: {t.id}
                Path:     {t.path}
                Title:    {t.title}
                Artist:   {t.artist}
            """)
        if more_files_to_report:
            print("There were more paths than listed that were not found")


def update_bitrates(session):
    """
    Update bitrates on all tracks in database
    """

    for track in Tracks.get_all(session):
        try:
            t = get_tags(track.path)
            track.bitrate = t["bitrate"]
        except FileNotFoundError:
            continue
