from peewee import *
import flask.ext.whooshalchemy
import datetime

db = MySQLDatabase('inventory', user="root", password="")

class BaseModel(Model):
	class Meta:
		database = db

class Device(Model):

	__searchable__ = [
		'SerialNumber',
		'SerialDevice'
		'Type',
		'Description',
		'Issues',
		'PhotoName',
		'Quality'
	]

	SerialNumber = CharField(primary_key=True)
	SerialDevice = CharField()
	Type = CharField()
	Description = TextField()
	Issues = TextField()
	PhotoName = CharField()
	Quality = CharField()
	
	class Meta:
		database = db
	
class Log(Model):
	
	Identifier = IntegerField()
	SerialNumber = ForeignKeyField(Device)
	UserIdentifier = CharField()
	Purpose = TextField()
	DateOut = DateTimeField(default=datetime.datetime.now)
	DateIn = DateTimeField(default=datetime.datetime.now)
	AuthorizerIdentifier = CharField()
	
	class Meta:
		database = db

def getDeviceTypes():
	types = [];

	query = Device.select(Device.Type).order_by(Device.Type)
	for q in query:
		if (doesEntryExist(q.Type, types) == True):
			pass
		else:
			types.append(q.Type)

	return types
	
def getStates():
	states = ["Operational"];

	query = Device.select(Device.Quality).order_by(Device.Quality)
	for q in query:
		if (doesEntryExist(q.Quality, states) == True):
			pass
		else:
			states.append(q.Quality)

	return states

def doesEntryExist(x, arr):
	for a in arr:
		if x == a:
			return True
	return False



@@ -121,11 +121,15 @@
 rd=%22
+root
 %22)%0A
-
 %0Acla
@@ -586,15 +586,18 @@
 r = 
-Integer
+PrimaryKey
 Fiel
@@ -638,16 +638,42 @@
 d(Device
+, db_column='SerialNumber'
 )%0A%09UserI
@@ -842,25 +842,46 @@
 horizerI
-dentifier
+n = CharField()%0A%09AuthorizerOut
  = CharF
@@ -879,33 +879,32 @@
 t = CharField()%0A
-%09
 %0A%09class Meta:%0A%09%09
@@ -1455,9 +1455,530 @@
  False%0A%0A
+def getNextSerialNumber(device_type):%0A%09querySerial = Device.select(Device.SerialNumber).where(Device.Type == device_type).order_by(Device.SerialNumber)%0A%09nextSerial=%22LCDI-%22%0A%09%0A%09numberOfEntries = len(querySerial)%0A%09prefix = 0%0A%09%0A%09if numberOfEntries %3C= 0:%0A%09%09prefix = len(getDeviceTypes())%0A%09else:%0A%09%09prefix = querySerial.get().SerialNumber%5Blen(nextSerial)%5D%0A%09%0A%09if numberOfEntries %3C 99:%0A%09%09nextSerial += str(prefix) + str(numberOfEntries).zfill(2)%0A%09else:%0A%09%09return %22OVERFLOW ERROR (MORE THAN 100 ITEMS PER TYPE)%22%0A%09%0A%09return nextSerial
 %0A

Update models for new schema, Add getting new serial numbers from a device type