# -*- coding: utf-8 -*-

import sqlite3
import os
import ApiItem


class ApiPipeline(object):
	db_filename = ''
	conn = None

	def __init__(self, DB_NAME):
		self.db_filename = DB_NAME
		print '# DB name: ' + DB_NAME
		self.conn = None

	def insert_into_DB(self, item):

		one = self.conn.execute('select * from apiinfo where mtdsig = ? AND restrname = ? AND specifier = ?', (item.mtdsig,item.restrname, item.specifier,)).fetchone()
		# if this app info is not in database, then insert it, or just skip
		if one is None:
			try:
				self.conn.execute('insert into apiinfo(clsname, mtdname, restrname, specifier, mtdsig, apilevel, summary, description, perms) values(?, ?, ?, ?, ?, ?, ?, ?, ?)',
			 					(item.clsname, item.mtdname, item.restrname, item.specifier, item.mtdsig, item.apilevel,item.summary,item.description, item.perms))
			except sqlite3.IntegrityError:
				print 'Integrity Error'
		else:
			self.update_row(item)
		self.conn.commit()

	def process_item(self, item):
		self.insert_into_DB(item)
		return item
	
	def initialize(self):
		print '# initialize: ' + self.db_filename
		if os.path.exists(self.db_filename):
			self.conn = sqlite3.connect(self.db_filename)
		else:
			print '####### no db'
			self.create_table()
			# self.conn = sqlite3.connect(self.db_filename)
			# self.cursor = self.conn.cursor()
		# self.conn.execute('PRAGMA journal_mode=WAL;')
		# self.conn.execute('PRAGMA foreign_keys = ON;')
		self.conn.commit()

	def finalize(self):
		if self.conn is not None:
			self.conn.commit()
			self.conn.close()
			self.conn = None

	# create tables if database file does not exist
	def create_table(self):
		print '#### Crate database'
		self.conn = sqlite3.connect(self.db_filename)
		self.conn.execute("create table apiinfo ( \
						id integer not null primary key autoincrement unique, \
						clsname text not null, \
						mtdname text, \
						restrname text, \
						specifier  text, \
						mtdsig text not null, \
						apilevel text, \
						summary text, \
						description text, \
						perms text \
						)")
		self.conn.commit()

	def update_row(self, item):
		self.conn.execute('update apiinfo set clsname = ?, mtdname = ?, restrname = ?, specifier = ?, apilevel = ?, summary = ?, description = ?, perms = ? where mtdsig = ?',
			 (item.clsname, item.mtdname, item.restrname, item.specifier, item.apilevel,item.summary,item.description, item.perms, item.mtdsig,))
		self.conn.commit()

	# def update_name_summary_desc(self, app_name,app_summary,app_description, apkname):
	# 	self.conn.execute('update appinfo set appname = ?, summary = ?, description = ? where apkname = ?', (app_name,app_summary,app_description, apkname,))
	# 	self.conn.commit()

	# def update_pkgname_mainaty_permissions(self, apppath,pkgname,mainaty, permissions):
	# 	self.conn.execute('update appinfo set pkgname = ?, mainaty = ?, permissions = ? where apppath = ?', (pkgname,mainaty, permissions, apppath,))
	# 	self.conn.commit()

	def get_api_by_sig(self,sig):
		one = self.conn.execute('select * from apiinfo where mtdsig = ?', (sig,)).fetchone()
		self.conn.commit()
		return one
	
	def get_apis(self):
		one = self.conn.execute('select * from apiinfo')
		self.conn.commit()
		return one

	def get_api_by_sig_and_specifier(self,sig,specifier):
		if specifier is None:
			return specifier
		one = self.conn.execute('select * from apiinfo where mtdsig = ?, specifier = ?', (sig,specifier,)).fetchone()
		self.conn.commit()
		return one

	def  get_api_by_sig_restrname_specifier(self,sig,restrname,specifier):
		one = self.conn.execute('select * from apiinfo where mtdsig = ? AND restrname = ? AND specifier = ?', (sig,restrname,specifier,)).fetchone()
		self.conn.commit()

		return one
	
	def  getapi_summary_descr_perm_by_name(self,cls_name,mtd_name,restrname):
		if not self.conn:
			self.conn = sqlite3.connect(self.db_filename)
		if restrname:
			one = self.conn.execute('select * from apiinfo where clsname = ? AND mtdname = ? AND restrname = ?', (cls_name,mtd_name,restrname,)).fetchone()
		else:
			one = self.conn.execute('select * from apiinfo where clsname = ? AND mtdname = ?', (cls_name,mtd_name,)).fetchone()
		self.conn.commit()
		if one is None:
			return None
		return " ".join(str(x) for x in one[7:]  if x != None)
