#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Functions managing the several directory names.
"""

# System modules
import shutil
from pathlib import Path

# Third-party modules
from astropy.io import fits
from astropy.time import Time

# Custom modules
#from utils.logger import log
from config.constants import (data_folder, dateobs, dir_type, ext, fits_folder,
                              frame_number, imagetyp, log_folder, focus_folder, log_ext, focus_ext, prefix)


def date_folder():
    """
    Create a date folder
    """

    now = Time.now()  # 2021-12-28T10:00:00.123456
    if now.datetime.hour < 12:  # from midnight to midday...
        folder_date = now - 1  # ...subtract one day
    else:
        folder_date = now

    # 2021-12-27
    folder_name = str(folder_date).split()[0]

    return folder_name


def frame_folder(header):
    """
    Create a folder depending on the image type in FITS header
    """

    frame = header[imagetyp]
    # Takes
    # frame_type or frame_number

    if isinstance(frame, int):
        # 1 -> object/
        folder_name = dir_type[frame]
    else:  # str
        # 'Light Frame' -> Light -> [1] -> 1
        frame = [v for k, v in frame_number.items() if k in frame][0]
        # 1 -> object/
        folder_name = dir_type[frame]

    return folder_name


def fits_path(header, dry=False):
    """
    Create a fits file path where the file will be stored
    """

    # data/fits/
    root = Path(data_folder, fits_folder)

    # 2021-12-27
    date = date_folder()
    date = Path(date)

    # 'Light Frame' -> Light -> object/
    frame = frame_folder(header)
    frame = Path(frame)

    # data/fits/2021-12-27/object/OARPAF.blabla.fits
    path = [root, date, frame]
    path = Path.joinpath(*path)

    if not dry:
        path.mkdir(parents=True, exist_ok=True)

    return path


def log_path(timestamp, dry=False):
    """
    Create the log file name and its path
    """

    # data/log/
    root = Path(data_folder, log_folder)
    path = root

    if not dry:
        path.mkdir(parents=True, exist_ok=True)

    # OARPAF.2021-12-27.log
    outfile = prefix + timestamp + log_ext

    # data/log/OARPAF.2021-12-27.log
    outpath = Path.joinpath(path, outfile)

    return outpath

def foc_path(timestamp, dry=False):
    """
    Create the focus output text file name and its path
    """

    # data/focus/
    root = Path(data_folder, focus_folder)
    path = root

    if not dry:
        path.mkdir(parents=True, exist_ok=True)

    # OARPAF.2021-12-27.foc
    outfile = prefix + timestamp + focus_ext

    # data/focus/OARPAF.2021-12-27.foc
    outpath = Path.joinpath(path, outfile)

    return outpath


def save_filename(infile):
    """
    Save a fits file in its path with an ESO-style filename.
    """

    inpath = Path(infile)

    header = fits.getheader(infile)

    # '2021-12-28T20:09:56.163'
    name = Time(header[dateobs]).isot
    # "OARPAF." + name + ".fits"
    outfile = Path(prefix + name + ext)

    # data/fits/2021-12-27/object/OARPAF.blabla.fits
    outdir = fits_path(header)

    outpath = Path.joinpath(outdir, outfile)

    shutil.copy2(inpath, outpath)  # For Python 3.8+.

    return outpath
