#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
	sqlite3 base class
	
"""

import sqlite3
import linecache
import sys


#from lib.logmanager import LogManager,LOG_ARGVAL,LOG_INFO,LOG_INFOSETTING,LOG_WARNING,LOG_ERROR,LOG_DEBUG,LOG_FATAL  


"""

Exemple d'usage : 

def transactions_by_date(self, date):
	sql = "SELECT * FROM transactions WHERE transaction_date = ?"
	return self.query(sql, (date,))


Exemple d'usage : 

with Database('my_db.sqlite') as db:
	db.execute('CREATE TABLE comments(pkey INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR, comment_body VARCHAR, date_posted TIMESTAMP)')
	db.execute('INSERT INTO comments (username, comment_body, date_posted) VALUES (?, ?, current_date)', ('tom', 'this is a comment'))
	comments = db.query('SELECT * FROM comments')
	print(comments)
	


"""
class Sqlitedb:
	
	lastError = None
	
	def __init__(self, name):
	
		self.lastError = None
		#self.log = LogManager( AppSetting.get('app', 'logfile') )		
		#self.log.logMessage( LOG_DEBUG , 'Start refresh data : phone.') 
		try:
			self._conn = sqlite3.connect(name)
			self._conn.row_factory = sqlite3.Row
			self._cursor = self._conn.cursor()
			self.execute("PRAGMA foreign_keys = 1")
			
		except Exception as e:  
					  
			self.lastError = str(e)
			self.PrintException()   

	def PrintException(self):
		exc_type, exc_obj, tb = sys.exc_info()
		f = tb.tb_frame
		lineno = tb.tb_lineno
		filename = f.f_code.co_filename
		linecache.checkcache(filename)
		line = linecache.getline(filename, lineno, f.f_globals)
		print ('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
						
	def __enter__(self):
		return self

	def __exit__(self, exc_type, exc_val, exc_tb):
		self.close()

	@property
	def connection(self):
		return self._conn

	@property
	def cursor(self):
		return self._cursor

	def commit(self):
		self.lastError = None
		try:
			self.connection.commit()            
		except Exception as e:            
			self.lastError = str(e)
			self.PrintException()   

	def close(self, commit=True):
		self.lastError = None
		try:
			if commit:
				self.commit()
			self.connection.close()
		except Exception as e:            
			self.lastError = str(e)
			self.PrintException()   

	def execute(self, sql, params=None):
		self.lastError = None
		self.lastInsertId = None
		try:
			self.cursor.execute(sql, params or ())
			self.lastInsertId = self.cursor.lastrowid			
			return True
			
		except Exception as e:            
			self.lastError = str(e)
			self.PrintException()   
			return False

	def fetchall(self):
		self.lastError = None
		try:
			return self.cursor.fetchall()
		except Exception as e:            
			self.lastError = str(e)
			self.PrintException()   
		return False        

	def query(self, sql, params=None):
		self.lastError = None
		try:
			self.cursor.execute(sql, params or ())
			results = [dict(row) for row in self.fetchall()]
			return results
		except Exception as e:            
			self.lastError = str(e)
			self.PrintException()   
		return False        

 
