#!/usr/bin/python
# -*- coding: utf-8 -*-

# PiAnoS (Picture Annotation System), A fingerprint examiner training tool
# Copyright (C) 2011-2012 University of Lausanne, Switzerland
# https://ips-labs.unil.ch/pianos

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see http://www.gnu.org/licenses/.


import udb
import pg
import os
import PIL.Image
import cStringIO as StringIO
import sys

def microdb_main(db):
	print "      Initializing PiAnoS 4"
	print "        Registering administrator"
	db.query("SELECT set_config('unil.user', (SELECT person.id FROM person,membership,pgroup WHERE person.id = membership.person AND membership.pgroup = pgroup.id AND pgroup.tutors IS true ORDER BY person.id ASC LIMIT 1)::text, false);")
	
	if sys.platform != 'win32':
		print "        Setting locales to *.UTF-8"
		db.query("UPDATE language SET short = short || '.UTF-8' WHERE short NOT ILIKE '%utf%';")
	
	is_lab_edition = db.query("SELECT count(*) FROM pg_tables WHERE tablename = 'assignment'")[0]['count'] == 0
	
	if is_lab_edition:
		init_le(db)
	else:
		init_te(db)
		
		
		
def init_te(db):
	
	print "      Initializing PiAnoS 4 - Teaching Edition"

	if db.query("SELECT count(*) FROM image;")[0]['count'] == 0 and db.query("SELECT count(*) FROM pgroup WHERE name = 'Default users'")[0]['count'] > 0:
		
		print "        Creating initial PiAnoS 4 dataset"
		
		images = [
			('../debug_prints/print.jpg','PRINT'),
			('../debug_prints/trace.jpg','MARK')
		]

		ids = {}

		for image in images:
			
			filename = os.path.join(os.path.split(__file__)[0],image[0])
			surface = PIL.Image.open(filename)
			
			handle = file(filename,'rb')
			buffer = handle.read()
			handle.close()
			
			res = db.query("INSERT INTO image(type,name,mimetype,resolution,width,height,data) VALUES ((SELECT ImageType.ID FROM ImageType WHERE Short = E'"+pg.escape_string(image[1])+"'),E'"+pg.escape_string(os.path.split(image[0])[1])+"','image/jpeg',"+str(surface.info['dpi'][0])+","+str(surface.size[0])+","+str(surface.size[1])+",E'"+pg.escape_bytea(buffer)+"') RETURNING id;")
			imgid = int(res[0]['id'])

			print "          Inserted image " + image[0] + " as ID " + str(imgid)

			ids[image[1]] = imgid
		
		defgroupID = db.query("SELECT id FROM pgroup WHERE name = 'Default users'")[0]['id']
		
		folderID = db.query("INSERT INTO folder(name) VALUES ('Default folder') RETURNING id;")[0]['id']
		db.query("INSERT INTO security(object,trustee) VALUES ("+str(folderID)+","+str(defgroupID)+");")
		print "          Created default folder as ID",folderID
		
		exID = db.query("INSERT INTO exercise(name,description,folder,mark,print) VALUES ('Default exercise','You may write a brief description of the exercise here',"+str(folderID)+","+str(ids['MARK'])+","+str(ids['PRINT'])+") RETURNING id;")[0]['id']
		print "          Created default exercise as ID",exID

def init_le(db):

	print "      Initializing PiAnoS 4 - Lab Edition"
	print ""
	
	return 0


