#!/usr/bin/env python

"""
Get EXIF information from image
"""
from uu import Error

import exifread
from datetime import datetime
from lumberjack import timber

log = timber(__name__)

def get_exif_date(tags,tag,f):
    t = ''
    log.debug(f'function: get_exif_tag(tags:{tags},tag:{tag},format:{f}')
    try:
        t = datetime.strptime(str(tags[tag]),f)
    except:
        pass
        # log.debug(f'Error: {e}. Format: {f}')

    return t

def get_os_ctime(path):
    # Don't pull the file ctime anymore, more often than not, it's wrong.
    # t = datetime.fromtimestamp(os.path.getctime(path))

    #raise an error so it will except and move on.
    raise ValueError(f"{path}: Using ctime like this is usually not good.")


def set_generic_date_time(date = '1900:01:01',
                          time = '00:00:00',
                          f = '%Y:%m:%d %H:%M:%S'):

    t = datetime.strptime(str(f'{date} {time}'),f)
    return t


def get_img_date(p):
    with open(p, 'rb') as file:
        tags = exifread.process_file(file)

        if 'Composite DateTimeOriginal' in tags:
            get_exif_date(tags,'Composite DateTimeOriginal','%Y:%m:%d %H:%M')

def get_exif_tag(p,t):
    with open(p, "rb") as f:
        try:
            tags = exifread.process_file(f)
            print(f'{p}: {tags}')
        except Error as e:
            return f'Received Error: {e} when trying to open {p}'
        finally:
            f.close()

    for tag in tags:
        print(tag)
        if t in tag.lower():
            print(tags[tag])
            return tags[tag]
        else:
            pass

def get_image_date(path):
    t = ''
    exif_dt = ''

    with open(path, "rb") as file:
        try:
            tags = exifread.process_file(file)
        except Error as e:
            log.error(e)
        finally:
            file.close()

    for tag in tags:
        if "DateTime" in tag:
            t = tag
            break

    if '' == t:
        exif_dt = set_generic_date_time()
    else:
        for f in ['%Y:%m:%d %H:%M:%S',
                  '%Y/%m/%d %H:%M:%S',
                  '%Y-%m-%d-%H-%M-%S']:
            log.debug(f'Trying... {t}, {f}, {path} ')
            exif_dt = get_exif_date(tags, t, f)

            if '' != exif_dt:
                break

    if '' == exif_dt:
        exif_dt = set_generic_date_time()
        # s = get_os_ctime(path) # This could produce wildly incorrect results
    return exif_dt