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

# System modules
from astropy.time import Time
from astropy.io import fits
from pathlib import Path
import shutil

# Custom modules
#from utils.logger import log
from config.constants import frame_number, dir_number
from config.constants import frame_type, dir_type
from config.constants import imagetyp, dateobs
from config.constants import prefix, ext
from config.constants import data_folder, fits_folder, log_folder

def date_folder():

    now = Time.now() # 2021-12-28T10:00:00.123456
    day = now.datetime.day # 28
    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):

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

    if type(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):

    # 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(infile, dry=False):

    # 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+infile

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


def save_filename(infile):
    
    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
