#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlite3
import os
class ImageString(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 imagestring where imagepath = ?', (item['imagepath'],)).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 imagestring(imagepath,imagepkg,imageaty,jsonstr,screenshotstr,googleimagestr,msazurestr,tineyestr,sametoid) values(?, ?, ?, ?, ?, ?, ?, ?, ?)',
			 					(item['imagepath'],item['imagepkg'],item['imageaty'],item['jsonstr'],item['screenshotstr'],item['googleimagestr'],item['msazurestr'],item['tineyestr'],item['sametoid']))
			except sqlite3.IntegrityError:
				print 'Integrity Error'
		else:
			self.update_row(item)
		self.conn.commit()

	def update_row(self, item):
		self.conn.execute('update imagestring set imagepkg = ?, imageaty = ?, jsonstr = ?, screenshotstr = ?, googleimagestr = ?, msazurestr = ?, tineyestr = ?, sametoid = ? where imagepath = ?',
			 (item['imagepkg'],item['imageaty'],item['jsonstr'],item['screenshotstr'],item['googleimagestr'],item['msazurestr'],item['tineyestr'],item['sametoid'], item['imagepath'],))
		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 imagestring ( \
						id integer not null primary key autoincrement unique, \
						imagepath text not null, \
						imagepkg text not null, \
						imageaty text not null, \
						jsonstr text, \
						screenshotstr text, \
						googleimagestr text, \
						msazurestr text, \
						tineyestr text, \
						sametoid integer \
						)")
		self.conn.commit()

	def get_json_string(self, imagepath):
		cursor = self.conn.execute('select jsonstr from imagestring where imagepath = ?',(imagepath,)).fetchone()
		self.conn.commit()
		# jsonstrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		if not cursor:
			return None
		return cursor[0]
	
	def get_image_path(self):
		cursor = self.conn.execute('select imagepath from imagestring')
		self.conn.commit()
		imagepaths = [imagepath[0] for imagepath in cursor if imagepath[0]]
		
		return imagepaths

	def	update_image_paths(self):
		cursor = self.conn.execute('select * from imagestring')
		self.conn.commit()
		imagestrings = [imagestring for imagestring in cursor if imagestring]

		for imagestring in imagestrings:
			ipath = imagestring[1]
			image_name = ipath.split('/')[-1].replace('state','screen')
			image_path = os.path.join('/'.join(ipath.split('/')[:-1]), image_name)
			print image_path
			print ipath
			self.conn.execute('UPDATE imagestring SET imagepath = ? where id = ?',(image_path,imagestring[0],))
			self.conn.commit()
	
	def get_googleimagestr(self,imagepath):
		cursor = self.conn.execute('select googleimagestr from imagestring where imagepath = ?',(imagepath,)).fetchone()
		self.conn.commit()
		# googleimagestrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		return cursor[0]

	def update_googleimagestr(self, imagepath,image_topic_str):
		self.conn.execute('update imagestring set googleimagestr = ? where imagepath = ?',
			 (image_topic_str,imagepath,))
		self.conn.commit()

	def get_screenshot_str(self,imagepath):
		cursor = self.conn.execute('select screenshotstr from imagestring where imagepath = ?',(imagepath,)).fetchone()
		self.conn.commit()
		# googleimagestrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		return cursor[0]
	def	update_json_str(self,imagepath,json_str):
		self.conn.execute('update imagestring set jsonstr = ? where imagepath = ?',
			 (json_str,imagepath,))
		self.conn.commit()

	def update_screenshot_str(self, imagepath,screenshot_str):
		one = self.conn.execute('update imagestring set screenshotstr = ? where imagepath = ?',
			 (screenshot_str,imagepath,))
		self.conn.commit()


	def get_tineye_str(self, imagepath):
		cursor = self.conn.execute('select tineyestr from imagestring where imagepath = ?',(imagepath,)).fetchone()
		self.conn.commit()
		# googleimagestrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		return cursor[0]

	def update_tineye_str(self, imagepath,tineye_str):
		self.conn.execute('update imagestring set tineyestr = ? where imagepath = ?',
			 (tineye_str,imagepath,))
		self.conn.commit()
	
	def get_json_screenshot_imageaty(self,imagepath):
		cursor = self.conn.execute('select jsonstr,screenshotstr,imageaty from imagestring where imagepath = ?',(imagepath,)).fetchone()
		self.conn.commit()
		# googleimagestrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		return cursor

	def get_multi_json_screenshot_googleimagestr(self,imagepath):
		cursor = self.conn.execute('select imagepath,jsonstr,screenshotstr,googleimagestr,imageaty from imagestring where instr(imagepath, ?) > 0',(imagepath,))
		self.conn.commit()
		# googleimagestrs = [jsonstr[0] for jsonstr in cursor if jsonstr[0]]
		if not cursor:
			return None
		return [item for item in cursor]

	def add_column(self):
		self.conn.execute("ALTER TABLE imagestring ADD COLUMN referkeywords text")
		self.conn.commit()
