#!/usr/bin/python3
"""
lark
Verify and sort game ROM images.

Intended features:
    DAT downloading
    File validation
    File renaming/moving
    Nice Beets-inspired UI.
    Release grouping (maybe, this might require another large external database)

UI notes

# Key terms
    - hash          Unique identifier for each ROM image.
    - image         ROM image, ripped from physical media.
    - dat           List of hashes, with associated filenames.
    - platform      The original hardware on which the image was intended to run.

# Verbs
    - list [hash, dat, platform, image]
        List items in the database.

    - import [datfile, imagefile]
        Process and add external items to the database.

    - add [platform, hash]
        Manually add items to the database.

    - remove [hash, dat, platform]
        Delete items from the database.
"""
# TODO: Write decent UI
import hashlib
import sys
import os
import uuid
import xdg.BaseDirectory

import dat
import hashdb

HASH_CHUNK_SIZE = 10485760 # 10mb
SQLITE_FILENAME = 'metadata.db'

data_path = os.path.join(xdg.BaseDirectory.xdg_data_home, 'lark')

def get_sha1sum(filename):
    sha1sum = hashlib.sha1()
    with open(filename, 'rb') as file_contents:
        while True:
            chunk = file_contents.read(HASH_CHUNK_SIZE)
            if not chunk:
                break
            sha1sum.update(chunk)

    return sha1sum.hexdigest()


'''
smd_dat = dat(SMD_DAT_PATH)
# TODO: Default to '.'
# TODO: Use a proper arg parser.
search_dir = sys.argv[1]
for filename in os.listdir(search_dir):
    # TODO: Ignore or descend into directories.
    # TODO: Compare hashes
    file_path = os.path.abspath(os.path.join(search_dir, filename))
    file_sha1 = get_sha1sum(file_path)
    search_result = smd_dat.search_by_sha1(file_sha1)
    if search_result:
        rom_data = search_result[0]
        print('File %s matches database entry for %s.' % (filename, rom_data.filename))
    else:
        print('File %s is not in database.' % filename)
'''
# Test code! :D
# TODO: Write test code that doesn't depend on external resources.
SMD_DAT_PATH = '/home/lumia/Downloads/Sega - Mega Drive - Genesis (20200303-035539).dat'
TEST_HASH = 'cfbf98c36c776677290a872547ac47c53d2761d6'

action_object = sys.argv[1]
action = sys.argv[2]

db = hashdb.MetadataDB(os.path.join(data_path, SQLITE_FILENAME))

# TODO: Use a real UI library. This one is just intended for development.
if action_object == 'platform':
    if action == 'add':
        print('add a platform')
        platform_uuid = uuid.uuid4()
        platform_shortcode = sys.argv[3]
        platform_name = sys.argv[4]

        platform_data = hashdb.PlatformData(UUID=str(platform_uuid), shortcode=platform_shortcode,
                                            name=platform_name)

        print(platform_data)

        db.add_platform(platform_data)

    if action == 'list':
        # TODO: convert this into a dict before passing.
        # TODO: Abstract out constraint parsing etc.
        constraints = sys.argv[3:]
        platform_results = db.search_platforms()
        print(platform_results)

    if action == 'remove':
        constraints = sys.argv[3:]
        db.remove_platform(constraints)
else:
    print('Unknown object.')
