#From SSR-net
# source file (https://github.com/shamangary/SSR-Net/blob/master/training_and_testing/TYY_utils.py)
# source file LICENSE ( https://github.com/shamangary/SSR-Net/blob/master/LICENSE)
#Line 38 was modified from SSR-net

from scipy.io import loadmat
from datetime import datetime
import os
import numpy as np

def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    # assume the photo was taken in the middle of the year
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1


def get_meta(mat_path, db):
    meta = loadmat(mat_path)
    full_path = meta[db][0, 0]["full_path"][0]
    dob = meta[db][0, 0]["dob"][0]  # Matlab serial date number
    gender = meta[db][0, 0]["gender"][0]
    photo_taken = meta[db][0, 0]["photo_taken"][0]  # year
    face_score = meta[db][0, 0]["face_score"][0]
    second_face_score = meta[db][0, 0]["second_face_score"][0]
    age = [calc_age(photo_taken[i], dob[i]) for i in range(len(dob))]

    return full_path, dob, gender, photo_taken, face_score, second_face_score, age


def load_data(mat_path):
    d = loadmat(mat_path)

    return d["image"], d["gender"][0], d["age"][0], d["db"][0], d["img_size"][0, 0], d["min_score"][0, 0]

def load_data_npz(npz_path):
    d = np.load(npz_path)
    a = d["image"]
    return a, d["age"], d["img_size"], d["age20"], d["age4"] ,d["age1"]

def mk_dir(dir):
    try:
        os.mkdir( dir )
    except OSError:
        pass
