#!/usr/bin/python
# vim: set fileencoding=utf-8 :

def print_help():
		print """== Syntax ==
katrin [params] <action> <object-type>

params
	Allowed all params for object-type. For detail see models.py files.
action
	add - add object. This action require all params of object, excluding id. If id not given, then it autogenerate.
	list - list id of objects given object-type
	del - del object. This action require id param
	show - show information about object
object-type
	Allowed all objects of django web interface. For detail see models.py files.

== Example of use ==

Add user:
	katrin --login 'test' --password '1' --lastname 'Aas' --firstname 'fqwef' --middlename 'fqweo' --balance '10' --credit '0' --blocked '0' --id '999' --tariffid 1 add user
List users id:
	katrin list users
Show user:
	katrin --id 20 show user
Delete user:
	katrin --id 20 del user"""

import sys
if len(sys.argv) < 2 :
	print_help()
	exit(1)


from django.core.management import setup_environ
sys.path.append('/var/www/html/addon-modules/katrin-web/')
import settings
setup_environ(settings)

from katrin.models import *
from traff.models import *
from tel.models import *
from ve.models import *

ALLOWED_MODELS = [
'Tariffs',
'Users',
'RefillLog',
'Refill',
'ServiceTelFilters',
'ServiceTelStats',
'ServiceTelUparams',
'ServiceTelStatsAggregate',
'ServiceTraffFilters',
'ServiceTraffStats',
'ServiceTraffStatsMonth',
'ServiceTraffStatsDay',
'ServiceTraffStatsHour',
'ServiceTraffUparams',
'HN',
'VE',
'ServiceVEUparams',
'ServiceVEFilters',
		]

long_args = []
for m in ALLOWED_MODELS:
	exec("long_args += [a+'=' for a in  [f.name for f in %s._meta.fields]]" % m);

import getopt
optlist, args = getopt.getopt(sys.argv[1:], '',
				long_args
				)

command=args[0]
obj_type=args[1]

# Подгонка типа объекта
obj_type = obj_type[0].upper()+obj_type[1:]
if obj_type not in ALLOWED_MODELS:
	obj_type += "s"
	if obj_type not in ALLOWED_MODELS:
		print "Wrong object type."
		print_help()

optlist = [ (tmp[0][2:],tmp[1]) for tmp in optlist] #обрезка -- в именах параметров
thedict = dict(optlist) # Словарь переданных параметров БЕЗ _id БЕЗ -- для добавления

try:
	id = thedict['id']
except:
	id=0
	thedict['id']=None

if command == "list":
	exec("t="+obj_type)
	for o in t.objects.all():
		print o.pk

elif command == "show":
	filter = ""
	for key in thedict.keys():
		if not (thedict[key] == None and key == "id"):
			filter += "%s=%s," % (key,thedict[key])
	filter = filter[0:len(filter)-1] # удаляем последнюю запятую
	exec("objs="+obj_type+".objects.filter("+filter+").values()")
	for obj in objs:
                for k in obj.keys():
			try:
				print u"%s=%s" % (k, obj[k])
			except:
				print k + '=' + (obj[k]).encode('utf-8')
elif command == "add":
	exec("o="+obj_type+"()")

	thelist = o.__dict__.keys()  # Нужные ключи для добавления с _id


	for k in thedict.keys(): # Добавляем где надо _id
		if not hasattr(o,k):
			thedict[k+"_id"] = thedict.pop(k)

	z = dict(map(lambda k: (k, thedict[k]), thelist)) # Оставляем только нужные элементы словаря

	o.__dict__ = z
	o.save()
	print "New object with id", o.pk, "was created"

elif command == "del":
	exec(obj_type+".objects.get(pk=id).delete()")
