#!/usr/bin/env python3

"""Convert devices information from devices.csv to java classes."""

import csv
import os
import shutil
import sys
from collections import Counter

print('Deleting old database...')
for i in range(25):
    api = '' if i == 0 else '-v' + str(i)
    db = 'database' + api + '/src/main/java/adila/db'
    shutil.rmtree(db, ignore_errors = True)
    os.makedirs(db)

with open('devices.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader)

    # Store all devices into a list
    print('Counting devices...')
    devices_list = []
    devices = []
    for row in reader:
        if not row[2] or not row[3]:
            print('Error at line %d: Device/Model field is empty' % reader.line_num)
            sys.exit(1)
        devices.append(row[2].lower())
        devices_list.append(row)
    print('Found %d devices' % len(devices))

    unique_devices = [k for k, v in Counter(devices).items() if v == 1]
    print('Found %d unique Build.DEVICE' % len(unique_devices))

    print('Creating database...')
    for device in devices_list:
        classname = ''

        # Fields
        manufacturer = device[0]
        name         = device[1]
        build_device = device[2]
        build_model  = device[3]
        series       = device[10]
        android_api  = device[12]

        ##### Build.DEVICE #####

        # Java class name cannot start with a number
        if build_device[0].isdigit():
            classname += '_'

        for d in build_device:
            if d.isalnum():
                classname += d.lower()
            else:
                classname += hex(ord(d))[2:]

        ##### Build.MODEL #####

        # Use Build.MODEL if Build.DEVICE is not unique
        if build_device not in unique_devices:
            classname += '_'

            for m in build_model:
                if m.isalnum():
                    classname += m.lower()
                else:
                    classname += hex(ord(m))[2:]

        # Java class file should be in its maximum supported API directory
        javadir = 'database'

        if android_api:
            javadir += '-v' + android_api.split()[-1]

        javadir += '/src/main/java/adila/db'

        # Create java class file
        with open(javadir + '/' + classname + '.java', 'x') as javafile:

            # Header
            content = '// This file is automatically generated.\n\n'
            # Package
            content += 'package adila.db;\n\n'
            # Comment
            content += '/*\n'
            content += ' * ' + manufacturer + ' ' + name + '\n'
            content += ' *\n'
            content += ' * DEVICE: ' + build_device + '\n'
            content += ' * MODEL: ' + build_model + '\n'
            content += ' */\n'
            # Class
            content += 'final class ' + classname + ' {\n'

            # Field
            content += '    public static final String DATA = "'

            # Data
            content += manufacturer + '|'             if manufacturer else '|'
            content += name.replace('"', '\\"') + '|' if name         else '|'
            content += series                         if series       else ''

            content += '";\n}\n'

            javafile.write(content)

    print('Done.')
