#!python
# -*- coding: UTF-8 -*-

# Formal
# ======
#
# Copyright 2013 Rob Britton
# Copyright 2015-2019 Heiko 'riot' Weinen <riot@c-base.org> and others.
#
# This file has been changed and this notice has been added in
# accordance to the Apache License
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# WiP! This is a prototype.

from pprint import pprint

input_data = """CREATE TABLE `example` (
  `id` int(23) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  UNIQUE KEY `id` (`id`),
  FULLTEXT KEY `flltxtIdx` (`email`),
)"""

create_statement, field_statements = input_data.split('(', maxsplit=1)

table_name = create_statement.split('`')[1]
print('Tablename:', table_name)

fields = {}
fulltext_indices = {}

for item in field_statements.replace('\n', '').split('  '):
    print('Orderitem:', item)

    if len(item) == 0:
        continue
    field_name_aggregation, field_type_aggregation = item.split('` ', maxsplit=1)

    field_name = field_name_aggregation.split('`')[1]

    field_enum = None
    field_default = None
    field_length = None

    # print('Fieldname:', field_name)

    if 'UNIQUE' in item:
        fields[field_name]['unique'] = True
        continue
    elif 'FULLTEXT' in item:
        things = item.split('`')
        index_name = things[1]
        fieldnames = things[1:]
        fulltext_indices[index_name] = fieldnames
        continue
    else:
        print('Normal item:', field_name)

        if field_type_aggregation.startswith('int'):
            field_type = 'integer'
        elif field_type_aggregation.startswith('varchar'):
            field_type = 'string'
        elif field_type_aggregation.startswith('enum'):
            field_type = 'string'
            field_enum = field_type_aggregation.split('enum(', maxsplit=1)[1].replace('\'', '').split(')', maxsplit=1)[
                0].split(',')
            print('Field enum:', field_enum)

        if 'DEFAULT' in field_type_aggregation:
            field_default = field_type_aggregation.split('DEFAULT ')[1].split(',')[0]
            print('Field default:', field_default)

        if not field_enum and field_type in ('string', 'integer'):
            field_length = int(field_type_aggregation.split('(', maxsplit=1)[1].split(')', maxsplit=1)[0])
            print('Field length:', field_length)

        field_not_null = 'NOT NULL' in field_type_aggregation

        print('Field Type:', field_type)
        print('Field not null:', field_not_null)

    field = {
        'type': field_type,
        'title': field_name,
        'description': "%s (%s, %s)" % (field_name, field_type, field_length)
    }

    if field_enum:
        field['enum'] = field_enum

    if field_length:
        if field_type == 'integer':
            field['maximum'] = pow(10, field_length) - 1
            field['minimum'] = 0
        if field_type == 'string':
            field['maxLength'] = field_length

    if field_default and field_default != 'NULL':
        if field_type == 'integer':
            field['default'] = int(field_default.rstrip('\'').lstrip('\''))
        else:
            field['default'] = field_default.rstrip('\'').lstrip('\'')

    fields[field_name] = field

pprint(fields)

pprint(fields.keys())

print('Done')
