#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
import os

class ScreenApiFlow(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 screenapiflow where appresultpath = ? And topaty = ? And senapi = ? And hashcode = ?', (item['appresultpath'],item['topaty'],item['senapi'],item['hashcode'],)).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 screenapiflow(appresultpath,topaty,senapi,hashcode,stacktrace,count,screenpkgname,screenaty,screenimagepath,label,solved) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
			 					(item['appresultpath'],item['topaty'],item['senapi'],item['hashcode'],item['stacktrace'],item['count'],item['screenpkgname'],item['screenaty'],item['screenimagepath'],item['label'],item['solved']))
			except sqlite3.IntegrityError:
				print 'Integrity Error'
		else:
			self.update_row(item)
		self.conn.commit()

	def update_row(self, item):
		self.conn.execute('update screenapiflow set stacktrace = ?, count = ?, screenpkgname = ?, screenaty = ?, screenimagepath = ?, label = ?, solved = ? where appresultpath = ? And topaty = ? And senapi = ? And hashcode = ?',
			 (item['stacktrace'],item['count'],item['screenpkgname'],item['screenaty'],item['screenimagepath'],item['label'],item['solved'],item['appresultpath'],item['topaty'],item['senapi'],item['hashcode'],))
		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.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 screenapiflow ( \
						id integer not null primary key autoincrement unique, \
						appresultpath text not null, \
						topaty not null, \
						senapi text not null, \
						hashcode integer not null, \
						stacktrace text, \
						count integer, \
						screenpkgname text, \
						screenaty text, \
						screenimagepath text, \
						label text, \
						solved integer \
						)")
		self.conn.commit()

	def get_screenimagepath(self):
		cursor = self.conn.execute('select appresultpath, screenimagepath from screenapiflow')
		self.conn.commit()
		screenimagepaths = [os.path.join(path[0],'droidbot/states',path[1]) for path in cursor if path[1]]
		return screenimagepaths

	def get_appresultpath_by_imagepath(self,imagepath):
		cursor = self.conn.execute('select appresultpath from screenapiflow where screenimagepath = ?',(imagepath,)).fetchone()
		self.conn.commit()
		# googleimagestrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		if not cursor:
			return None
		return cursor[0]


	def	get_flows(self):
		cursor = self.conn.execute('select * from screenapiflow')
		self.conn.commit()
		flows = [flow for flow in cursor if flow]
		return flows

	def get_flows_of_path(self,result_path):
		cursor = self.conn.execute('select * from screenapiflow where appresultpath = ?',(result_path,))
		self.conn.commit()
		flows = [flow for flow in cursor if flow]
		return flows

	def	get_appresultpaths(self):
		cursor = self.conn.execute('select appresultpath from screenapiflow')
		self.conn.commit()
		appresultpaths = [path[0] for path in cursor if path]
		return appresultpaths
	
	def	get_senapi(self):
		cursor = self.conn.execute('select senapi from screenapiflow')
		self.conn.commit()
		senapis = [senapi[0] for senapi in cursor if senapi]
		return set(senapis)

	def delete_flow_by_id(self,id):
		self.conn.execute('DELETE FROM screenapiflow WHERE id = ?', (id,))
		self.conn.commit()
	
	def update_flow_count_by_id(self,id, count):
		self.conn.execute('UPDATE screenapiflow SET count = ? where id = ?',(count,id,))
		self.conn.commit()
	
	def	update_screenimage_paths(self):
		cursor = self.conn.execute('select * from screenapiflow')
		self.conn.commit()
		flows = [flow for flow in cursor if flow]

		for flow in flows:
			ipath = flow[9]
			if ipath:
				
				image_path = ipath.split('/')[-1]
				print '++',image_path
				self.conn.execute('UPDATE screenapiflow SET screenimagepath = ? where id = ?',(image_path,flow[0],))
				self.conn.commit()
				# break
	def if_flow_exist(self,appresultpath,topaty,senapi,hashcode):
		one = self.conn.execute('select * from screenapiflow where appresultpath = ? And topaty = ? And senapi = ? And hashcode = ?', (appresultpath,topaty,senapi,hashcode,)).fetchone()
		if one is None:
			return None
		return one
