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


def extractor(dt_file, start, end):
    catalog = {}
    conn = sqlite3.connect(dt_file)
    cursor = conn.cursor()
    req = "SELECT id, model, lens, exposure, aperture, iso, focal_length, datetime_taken, width, height FROM images;"
    cursor.execute(req)
    res = cursor.fetchall()
    for data in res:
        img_date = datetime.strptime(data[7], "%Y:%m:%d %H:%M:%S")
        if start <= img_date <= end:
            catalog.update({
                data[0]:
                    {
                        'camera': data[1],
                        'lens': data[2],
                        'shutter': float(data[3]*1000),
                        'aperture': round(float(data[4]), 1),
                        'iso': int(data[5]),
                        'focal': float(data[6]),
                        'datetime': img_date,
                        'height': int(data[9]),
                        'width': int(data[8])
                }
            })
    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():
        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(round(float(catalog[item]['focal']), 1))
        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(catalog.keys()),
        "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="darktable library")
    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))
