#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sqlite3
from datetime import datetime


def extractor(lrcat_file, start, end):
    catalog, camera, lens = {}, {}, {}
    conn = sqlite3.connect(lrcat_file)
    cursor = conn.cursor()
    req = "SELECT id_local, value FROM AgInternedExifCameraModel"
    cursor.execute(req)
    res = cursor.fetchall()
    for data in res:
        camera.update({data[0]: data[1]})
    req = "SELECT id_local, value FROM AgInternedExifLens"
    cursor.execute(req)
    res = cursor.fetchall()
    for data in res:
        lens.update({data[0]: data[1]})
    req = "SELECT image, focalLength, aperture, isoSpeedRating, shutterSpeed, cameraModelRef, lensRef FROM AgHarvestedExifMetadata"
    cursor.execute(req)
    res = cursor.fetchall()
    for data in res:
        if data[2]:
            aperture = round(2**(data[2]/2), 1)
        if data[4]:
            shutter = round(1/(2**data[4])*1000, 4)
        catalog.update({int(data[0]): {'focal': data[1], 'aperture': aperture, 'iso': int(
            data[3]), 'shutter': shutter, 'camera': camera[data[5]], 'lens': lens[data[6]]}})
    req = "SELECT id_local, captureTime, fileHeight, fileWidth FROM Adobe_images"
    cursor.execute(req)
    res = cursor.fetchall()
    for data in res:
        catalog[int(data[0])].update(
                {'datetime': datetime.strptime(data[1], "%Y-%m-%dT%H:%M:%S"), 'height': int(data[2]), 'width': int(data[3])})
    cameras, lenses, focals, apertures, shutter_speeds = {}, {}, {}, {}, {}
    isos, dimensions, cameras_lenses, dates = {}, {}, {}, {}
    cameras_list, lenses_list, focals_list, apertures_list, shutter_speeds_list = [], [], [], [], []
    isos_list, dimensions_list, cameras_lenses_list, dates_list = [], [], [], []
    for item in catalog.keys():
        if start <= catalog[item]['datetime'] <= end:
            cameras_list.append(catalog[item]['camera'])
            lenses_list.append(catalog[item]['lens'])
            if catalog[item]['lens'] and "---" not in catalog[item]['lens']:
                cameras_lenses_list.append(
                    "{} + {}".format(catalog[item]['camera'], catalog[item]['lens']))
            focals_list.append(catalog[item]['focal'])
            apertures_list.append(catalog[item]['aperture'])
            shutter_speeds_list.append(catalog[item]['shutter'])
            isos_list.append(catalog[item]['iso'])
            dimensions_list.append(
                round(((catalog[item]['height']*catalog[item]['width'])/10**6), 1))
            dates_list.append(catalog[item]['datetime'].strftime("%Y%m%d"))
    for camera in list(set(cameras_list)):
        if camera:
            cameras.update({camera: cameras_list.count(camera)})
    for lens in list(set(lenses_list)):
        if lens and "---" not in lens:
            lenses.update({lens: lenses_list.count(lens)})
    for camera_lense in list(set(cameras_lenses_list)):
        if camera_lense:
            cameras_lenses.update(
                {camera_lense: cameras_lenses_list.count(camera_lense)})
    for focal in list(set(focals_list)):
        if focal:
            focals.update({focal: focals_list.count(focal)})
    for aperture in list(set(apertures_list)):
        if aperture:
            apertures.update({aperture: apertures_list.count(aperture)})
    for shutter_speed in list(set(shutter_speeds_list)):
        if shutter_speed:
            shutter_speeds.update(
                {shutter_speed: shutter_speeds_list.count(shutter_speed)})
    for iso in list(set(isos_list)):
        if iso:
            isos.update({iso: isos_list.count(iso)})
    for dimension in list(set(dimensions_list)):
        if dimension:
            dimensions.update({dimension: dimensions_list.count(dimension)})
    for date in list(set(dates_list)):
        if date:
            dates.update({date: dates_list.count(date)})
    return {
        "total": len(dimensions_list),
        "date": dates,
        "cameras": cameras,
        "lenses": lenses,
        "cameras+lenses": cameras_lenses,
        "focals": focals,
        "apertures": apertures,
        "shutter_speeds": shutter_speeds,
        "isos": isos,
        "dimensions": dimensions
    }


if __name__ == '__main__':
    import argparse
    import json
    parser = argparse.ArgumentParser()
    parser.add_argument("infile", help="lrcat file")
    parser.add_argument("-s", "--start-date", help="start date as YYYYMMDD. If omitted, begin of the collection.", const=None)
    parser.add_argument("-e", "--end-date", help="end date as YYYYMMDD. If omitted, today", const=None)
    args = parser.parse_args()
    if not args.start_date:
        args.start_date = "18250101" # Ok, that's the year of the 1st photography by Nicéphore Niépce. Shoul'd be enough for a start date.
    if not args.end_date:
        args.end_date = datetime.strftime(datetime.now(), "%Y%m%d")
    try:
        datetime.strptime(args.start_date, "%Y%m%d")
        datetime.strptime(args.end_date, "%Y%m%d")
    except ValueError:
        print("Date must be YYYYMMDD.")
        exit()
    print(json.dumps(extractor(args.infile, datetime.strptime(args.start_date, "%Y%m%d"), datetime.strptime(args.end_date, "%Y%m%d")), indent=4, sort_keys=True))
