#! /usr/bin/python
# -*- coding: iso-8859-1 -*-

#####################################################
#    Copyright (C) 2006 by Cesar Kallas   	
#    cesarkallas@soulivre.org   
#    http://cesarkallas.soulivre.org
#                                                                          
#    This program is free software; you can redistribute it and#or modify  
#    it under the terms of the GNU General Public License as published by 
#    the Free Software Foundation; either version 2 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 General Public License for more details.                          
#                                                                          
#    You should have received a copy of the GNU General Public License     
#    along with this program; if not, write to the                         
#    Free Software Foundation, Inc.,                                       
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             
#####################################################

import MySQLdb
import MySQLdb.cursors
import Log
import Ambiente

class Operadores(object):
	"""
		Classe que gerencia operadores
	"""
	
	def __init__(self):
		self.db = Ambiente.db
		
		# Inicia o log
		self.log = Log.Log("Operadores")
		self.log = self.log.get()
	
	def inseri(self, dicNovoOperador=None):
		"""
		Inseri um novo operador na base de dados
		Entrada: dicNovoOpeador = Dicionario com os campos de cadastro do Operador
		Retorno: 
			 1: concluido com sucesso
			None: falha na insercao
		"""
		if dicNovoOperador == None:
			return None
			
		try:
			# Inseri novo operador
			self.db.execute("REPLACE INTO operadores \
				(login, nome, nivel) \
				values (%s, %s, %s)",
				(dicNovoOperador["login"], dicNovoOperador["nome"], 
				dicNovoOperador["nivel"]))
			return 1
		except MySQLdb.Error, e:
			self.log.error("%d: %s" % (e.args[0], e.args[1]))
			return None
		except Exception:
			self.log.error("ao cadastrar novo operador")
			return None

	def atualiza(self, dicOperador):
		try:
			# Atualiza operador
			self.db.execute("""UPDATE operadores SET \
				nome = %s, nivel = %s, senha = %s""",  
				(dicOperador["nome"] , dicOperador["nivel"], dicOperador["senha"]))
			return 1
		except MySQLdb.Error, e:
			mysql_erro = "%d: %s" % (e.args[0], e.args[1])
			self.log.error(mysql_erro)
			raise
			return mysql_erro
		except Exception:
			erro = "ao atualizar operador: %s" % dicOperador
			self.log.error(erro)
			raise
			return erro
			
			
	def remove(self, login=None):
		"""
		Remove um operador da base de dados
		Entrada: login (login do operador)
		Retorno:
			 1: concluido com sucesso
			None: falha na remocao
		"""
		
		if login == None:
			return None
		
		try:
			self.db.execute("DELETE FROM operadores where login = %s", login)
			return 1
		except MySQLdb.Error, e:
			self.log.error("%d: %s" % (e.args[0], e.args[1]))
			return None


	def informacao(self, login=None):
		"""
		Retorna todas as informacoes de um operador
		Entrada: login (login do operador)
		Saida:
			OK: Informacoes do operador
			None: para falha
		"""
		try:
			if login == None:
				self.db.execute("""SELECT * FROM operadores""")
				return self.db.fetchall()	
			else:
				self.db.execute("""SELECT * FROM operadores WHERE login = %s""",  (login))
				return self.db.fetchone()
		except MySQLdb.Error, e:
			self.log.error("%d: %s" % (e.args[0], e.args[1]))
			return None

	
	def autentica(self, login=None, senha=None):
		"""
		Autentica um login e senha
		"""
		if login == None:
			return -1
		if senha == None:
			return -1
		
		try:
			self.db.execute("""SELECT login from operadores where login = %s and senha = %s""", (login, senha))
			resultado = self.db.fetchone()
			if  resultado == None:
				return -1
			else:
				return 1
		except MySQLdb.Error, e:
			self.log.error("%d: %s" % (e.args[0], e.args[1]))
			return None

	def total(self):
		"""
			Retorna o numero de operadores cadastrados
			None: para falha
		"""
		try:
			self.db.execute("SELECT count(*) as total FROM operadores")
			return self.db.fetchone()
		except MySQLdb.Error, e:
			self.log.error("%d: %s" % (e.args[0], e.args[1]))
			return None
