# -*- 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 re

def microdb_main(db):
	print "Installing the NIJ module for PiAnoS 4"
	
	filename = os.path.join(os.path.split(__file__)[0], 'pianos4-nij-survey.txt')
	content = file(filename,'r').read()
	
	# count the number of questions using a regex
	res = re.findall(r'(\d+)\s*\n(\S+)\s', content, re.MULTILINE)
	allq = filter(lambda x: x[1] in ('Radio','DropDown','TextArea'), res) # exclude non-question items
	count = len(allq)
	
	if db.query("SELECT count(*) FROM survey;")[0]['count'] == 0:
		print "  Creating survey from '"+filename+"' ..."
		db.query("INSERT INTO survey(name,definition,numquestions) VALUES (E'"+pg.escape_string('survey1')+"',E'"+pg.escape_string(content)+"',"+str(count)+");")
		print "  Done !"
	else:
		print "  Updating survey definition from '"+filename+"' ..."
		db.query("UPDATE survey SET definition = E'"+pg.escape_string(content)+"', numquestions = "+str(count)+" WHERE ID = (SELECT id FROM survey ORDER BY ID ASC LIMIT 1);")
		print "  Done !"
		
	# The NIJ study does not have an EVALUATION step, so remove it
	print "  Removing the EVALUATION step"
	db.query("DELETE FROM resultstep WHERE short = E'"+pg.escape_string('EVALUATION')+"';")
	
	
