"""
Oracle database backend for Django.

Requires cx_Oracle: http://www.computronix.com/utilities.shtml
"""

from django.core.db import base, typecasts
import cx_Oracle  as Database

#needed for fetchone, fetchmany, fetchall support
from django.core.db.dicthelpers import *


DatabaseError = Database.DatabaseError

class DatabaseWrapper:
    def __init__(self):
        self.connection = None
        self.queries = []

    def cursor(self):
        from django.conf.settings import DATABASE_USER, DATABASE_NAME, DATABASE_HOST, DATABASE_PASSWORD, DEBUG
        if self.connection is None:
            if DATABASE_NAME == '' or DATABASE_USER == '' or DATABASE_PASSWORD == '':
                from django.core.exceptions import ImproperlyConfigured
                raise ImproperlyConfigured, "You need to specify DATABASE_NAME, DATABASE_USER, and DATABASE_PASSWORD in your Django settings file."
            conn_string = "%s/%s@%s" % (DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)
            self.connection = Database.connect(conn_string)               
        return FormatStylePlaceholderCursor(self.connection)

    def commit(self):
        self.connection.commit()

    def rollback(self):
        if self.connection:
            self.connection.rollback()

    def close(self):
        if self.connection is not None:
            self.connection.close()
            self.connection = None

class FormatStylePlaceholderCursor(Database.Cursor):
    """
    Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var" style.
    This fixes it -- but note that if you want to use a literal "%s" in a query,
    you'll need to use "%%s" (which I belive is true of other wrappers as well).
    """
    
    def execute(self, query, params=[]):
        query = self.convert_arguments(query, len(params))
        return Database.Cursor.execute(self, query, params)
        
    def executemany(self, query, params=[]):          
        query = self.convert_arguments(query, len(params[0]))
        return Database.Cursor.executemany(self, query, params)
        
    def convert_arguments(self, query, num_params):
        # replace occurances of "%s" with ":arg" - Oracle requires colons for parameter placeholders.
        args = [':arg' for i in range(num_params)]
        return query % tuple(args)

def get_last_insert_id(cursor, table_name, pk_name):
    query = "SELECT %s_sq.currval from dual" % table_name
    cursor.execute(query)
    return cursor.fetchone()[0]

def get_date_extract_sql(lookup_type, table_name):
    raise NotImplementedError

def get_date_trunc_sql(lookup_type, field_name):
    raise NotImplementedError
    
def get_table_list(cursor):
    "Returns a list of table names in the current database."
    raise NotImplementedError

def get_relations(cursor, table_name):
    """
    Returns a dictionary of {field_index: (field_index_other_table, other_table)}
    representing all relationships to the given table. Indexes are 0-based.
    """
    raise NotImplementedError


OPERATOR_MAPPING = {
    'exact': '=',
    'iexact': 'LIKE',
    'contains': 'LIKE',
    'icontains': 'LIKE',
    'ne': '!=',
    'gt': '>',
    'gte': '>=',
    'lt': '<',
    'lte': '<=',
    'startswith': 'LIKE',
    'endswith': 'LIKE',
    'istartswith': 'LIKE',
    'iendswith': 'LIKE',
}

# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
DATA_TYPES = {
    'AutoField':         'number(38)',
    'BooleanField':      'number(1)',
    'CharField':         'varchar2(%(maxlength)s)',
    'CommaSeparatedIntegerField': 'varchar2(%(maxlength)s)',
    'DateField':         'date',
    'DateTimeField':     'date',
    'EmailField':        'varchar2(75)',
    'FileField':         'varchar2(100)',
    'FloatField':        'number(%(max_digits)s, %(decimal_places)s)',
    'ImageField':        'varchar2(100)',
    'IntegerField':      'integer',
    'IPAddressField':    'char(15)',
    'ManyToManyField':   None,
    'NullBooleanField':  'integer',
    'OneToOneField':     'integer',
    'PhoneNumberField':  'varchar(20)',
    'PositiveIntegerField': 'integer',
    'PositiveSmallIntegerField': 'smallint',
    'SlugField':         'varchar(50)',
    'SmallIntegerField': 'smallint',
    'TextField':         'long',
    'TimeField':         'timestamp',
    'URLField':          'varchar(200)',
    'USStateField':      'varchar(2)',
    'XMLField':          'long',
}

# Maps type codes to Django Field types.
DATA_TYPES_REVERSE = {
    16: 'BooleanField',
    21: 'SmallIntegerField',
    23: 'IntegerField',
    25: 'TextField',
    869: 'IPAddressField',
    1043: 'CharField',
    1082: 'DateField',
    1083: 'TimeField',
    1114: 'DateTimeField',
    1184: 'DateTimeField',
    1266: 'TimeField',
    1700: 'FloatField',
}

EMPTY_STR_EQUIV = ' '