from collections import namedtuple

import cx_Oracle

from django.db import models
from django.db.backends.base.introspection import (
    BaseDatabaseIntrospection, FieldInfo as BaseFieldInfo, TableInfo,
)
from django.utils.functional import cached_property

FieldInfo = namedtuple('FieldInfo', BaseFieldInfo._fields + ('is_autofield', 'is_json'))


class DatabaseIntrospection(BaseDatabaseIntrospection):
    cache_bust_counter = 1

    # Maps type objects to Django Field types.
    @cached_property
    def data_types_reverse(self):
        if self.connection.cx_oracle_version < (8,):
            return {
                cx_Oracle.BLOB: 'BinaryField',
                cx_Oracle.CLOB: 'TextField',
                cx_Oracle.DATETIME: 'DateField',
                cx_Oracle.FIXED_CHAR: 'CharField',
                cx_Oracle.FIXED_NCHAR: 'CharField',
                cx_Oracle.INTERVAL: 'DurationField',
                cx_Oracle.NATIVE_FLOAT: 'FloatField',
                cx_Oracle.NCHAR: 'CharField',
                cx_Oracle.NCLOB: 'TextField',
                cx_Oracle.NUMBER: 'DecimalField',
                cx_Oracle.STRING: 'CharField',
                cx_Oracle.TIMESTAMP: 'DateTimeField',
            }
        else:
            return {
                cx_Oracle.DB_TYPE_DATE: 'DateField',
                cx_Oracle.DB_TYPE_BINARY_DOUBLE: 'FloatField',
                cx_Oracle.DB_TYPE_BLOB: 'BinaryField',
                cx_Oracle.DB_TYPE_CHAR: 'CharField',
                cx_Oracle.DB_TYPE_CLOB: 'TextField',
                cx_Oracle.DB_TYPE_INTERVAL_DS: 'DurationField',
                cx_Oracle.DB_TYPE_NCHAR: 'CharField',
                cx_Oracle.DB_TYPE_NCLOB: 'TextField',
                cx_Oracle.DB_TYPE_NVARCHAR: 'CharField',
                cx_Oracle.DB_TYPE_NUMBER: 'DecimalField',
                cx_Oracle.DB_TYPE_TIMESTAMP: 'DateTimeField',
                cx_Oracle.DB_TYPE_VARCHAR: 'CharField',
            }

    def get_field_type(self, data_type, description):
        if data_type == cx_Oracle.NUMBER:
            precision, scale = description[4:6]
            if scale == 0:
                if precision > 11:
                    return 'BigAutoField' if description.is_autofield else 'BigIntegerField'
                elif 1 < precision < 6 and description.is_autofield:
                    return 'SmallAutoField'
                elif precision == 1:
                    return 'BooleanField'
                elif description.is_autofield:
                    return 'AutoField'
                else:
                    return 'IntegerField'
            elif scale == -127:
                return 'FloatField'
        elif data_type == cx_Oracle.NCLOB and description.is_json:
            return 'JSONField'

        return super().get_field_type(data_type, description)

    def get_table_list(self, cursor):
        """Return a list of table and view names in the current database."""
        cursor.execute("""
            SELECT table_name, 't'
            FROM user_tables
            WHERE
                NOT EXISTS (
                    SELECT 1
                    FROM user_mviews
                    WHERE user_mviews.mview_name = user_tables.table_name
                )
            UNION ALL
            SELECT view_name, 'v' FROM user_views
            UNION ALL
            SELECT mview_name, 'v' FROM user_mviews
        """)
        return [TableInfo(self.identifier_converter(row[0]), row[1]) for row in cursor.fetchall()]

    def get_table_description(self, cursor, table_name):
        """
        Return a description of the table with the DB-API cursor.description
        interface.
        """
        # user_tab_columns gives data default for columns
        cursor.execute("""
            SELECT
                user_tab_cols.column_name,
                user_tab_cols.data_default,
                CASE
                    WHEN user_tab_cols.collation = user_tables.default_collation
                    THEN NULL
                    ELSE user_tab_cols.collation
                END collation,
                CASE
                    WHEN user_tab_cols.char_used IS NULL
                    THEN user_tab_cols.data_length
                    ELSE user_tab_cols.char_length
                END as internal_size,
                CASE
                    WHEN user_tab_cols.identity_column = 'YES' THEN 1
                    ELSE 0
                END as is_autofield,
                CASE
                    WHEN EXISTS (
                        SELECT  1
                        FROM user_json_columns
                        WHERE
                            user_json_columns.table_name = user_tab_cols.table_name AND
                            user_json_columns.column_name = user_tab_cols.column_name
                    )
                    THEN 1
                    ELSE 0
                END as is_json
            FROM user_tab_cols
            LEFT OUTER JOIN
                user_tables ON user_tables.table_name = user_tab_cols.table_name
            WHERE user_tab_cols.table_name = UPPER(%s)
        """, [table_name])
        field_map = {
            column: (internal_size, default if default != 'NULL' else None, collation, is_autofield, is_json)
            for column, default, collation, internal_size, is_autofield, is_json in cursor.fetchall()
        }
        self.cache_bust_counter += 1
        cursor.execute("SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0".format(
            self.connection.ops.quote_name(table_name),
            self.cache_bust_counter))
        description = []
        for desc in cursor.description:
            name = desc[0]