from django.contrib.auth.models import User
from django.db import models
from myrig.computer.quantity import Quantity
from south.modelsinspector import add_introspection_rules

class SIIntegerField(models.PositiveIntegerField):
    '''
    Implements storage for a positive integer value of an SI unit
    '''
    
    __metaclass__ = models.SubfieldBase
    
    def __init__(self, unit, *args, **kwargs):
        '''
        Initializes the model field
        '''
        self.unit = unit
        super(SIIntegerField, self).__init__(*args, **kwargs)
    
    def to_python(self, value):
        '''
        Returns a Quantity object representing the value
        '''
        if isinstance(value, Quantity):
            return value
        elif value:
            return Quantity(int(value), self.unit)
        else:
            return None
    
    def get_prep_value(self, value):
        '''
        Returns a representation of the value suitable for the database
        '''
        return int(value)

# Allows the field to be used in South migrations
add_introspection_rules([
    (
        [SIIntegerField,],
        [],
        {
            'unit': ['unit', {},],
        },
    ),
], ['^myrig\.computer\.models\.SIIntegerField',])

class Manufacturer(models.Model):
    '''
    Represents a component manufacturer
    '''
    
    name = models.CharField(max_length=40,
                            help_text='The registered name of the company')
    website = models.URLField(null=True,
                              blank=True,
                              help_text='The official website of the company')

    def __unicode__(self):
        '''
        Returns a string representation of the company
        '''
        return self.name

class Component(models.Model):
    '''
    Represents an individual component
    '''
    
    manufacturer = models.ForeignKey(Manufacturer,
                                     help_text='The manufacturer of the component')
    model = models.CharField(max_length=40,
                             help_text='The model number of the component')
    
    def __unicode__(self):
        '''
        Returns a string representation of the component
        '''
        return self._format((
            self.manufacturer,
            self.model,
        ))
    
    def _format(self, values):
        '''
        Joins the values in the provided list that are nonzero
        '''
        return ' '.join((str(v) for v in values if v))

class Chipset(Component):
    '''
    Represents a chipset
    '''

class Processor(Component):
    '''
    Represents a processor
    '''
    
    series = models.CharField(max_length=40,
                              null=True,
                              blank=True,