import sqlite3
import sys
import os
import datetime
import time
import argparse

def get_browser_path(browser):
    #get the home directory operating system you are working on
    os_env_dir = os.path.expanduser('~')
    req_path = ""
    #print(os_env_dir)

    #check if the browser is firefox
    if browser == 'firefox':
        #set the path according to the operating system
        if sys.platform.startswith('win') == True:
            req_path = os_env_dir + "/AppData/Roaming/Mozilla/Firefox/Profiles/"
        elif sys.platform.startswith('linux') == True:
            req_path = os_env_dir + "/.mozilla/firefox/"
    elif browser == 'Chrome': #todo : implement it for chrome also
        if sys.platform.startswith('win') == True:
            req_path = os_env_dir + ''
        elif sys.platform.startswith('linux') == True:
            req_path = os_env_dir + "/.config/chromium/Default/History"

    return req_path


def clear_history_by_names(unwanted_names , ff_cursor , test = True):
    for name in unwanted_names:
        symbol = '%'+ name +'%'
        if test == False:
            print("Deleting History..................")
            ff_cursor.execute("DELETE FROM moz_places where url like ? or title like ?" , (symbol , symbol , ) )
        else:
            count = 1
            print("The following history items matched your query :")
            print("")
            for row in ff_cursor.execute("SELECT url FROM moz_places where url like ? or title like ?" , (symbol , symbol , ) ):
                print('%s. %s' %(count , row[0]))
                count+=1


def clear_history_by_time(starting_time , ending_time , ff_cursor , test = True):
	history_time = datetime.datetime.utcnow() - datetime.timedelta(hours = starting_time)
	final_starting_time = time.mktime(history_time.timetuple())
	final_starting_time = int(final_starting_time*1000000)
	history_time = datetime.datetime.utcnow() - datetime.timedelta(hours = ending_time)
	final_ending_time = time.mktime(history_time.timetuple())
	final_ending_time = int(final_ending_time*1000000)
	if test == True:
		count = 1
		print("The following history items matched your query: ")
		print("")
		for row in ff_cursor.execute("SELECT url FROM moz_places where last_visit_date > ? and last_visit_date < ?" , (final_starting_time , final_ending_time ,  )):
			print('%s. %s' %(count , row[0]))
			count+=1
	else:
		print("Deleting History................")
		ff_cursor.execute("DELETE FROM moz_places where last_visit_date > ? and last_visit_date < ?" , (final_starting_time , final_ending_time , ))



if __name__ == "__main__":
	#parsing
	parser = argparse.ArgumentParser(description="Manipulate your browsing history using keywords or timespan")
	mode = parser.add_mutually_exclusive_group()
	mode.add_argument("-d" , "--delete" , action="store_true" , help="Deletion mode: Actual deletion of history takes place.")
	mode.add_argument("-t" , "--test" , action="store_true" , help="Testing mode: selected history is just displayed (no actual deletion)")
	deleteBy = parser.add_mutually_exclusive_group()
	deleteBy.add_argument("-kw" , "--keywords" , action="store_true" , help="Deletion/Selection by keywords")
	deleteBy.add_argument("-ts" , "--timespan" , action="store_true" , help="Deletion/Selection by timespan")
	args = parser.parse_args()
	modeSelect = True
	if args.delete:
		test = False
	elif args.test:
		test = True
	else:
		modeSelect = False
	if modeSelect==False:
		print("Its good to close the browser before proceeding")
		print("Select the mode :")
		print("1. Testing mode (Selected history is just shown , no actual deletion)")
		print("2. Deletion node (Selected history is deleted permanently )")
		print("3. Exit")
		ch = int(input("Enter your choice (1 or 2 or 3) : "))
		if ch ==1:
			test = True
		elif ch == 2:
			test = False
		elif ch == 3:
			exit(1)
		else:
			print("No such option found")
			exit(1)
	#printing the choices
	ch = 0
	if args.keywords:
		ch = 1
	elif args.timespan:
		ch = 2
	else:
		print("Select the way you want to delete/filter you history: ")
		print("1. By certain keywords  2. By certain timespan ")
		ch = int(input("Enter your choice (1 or 2) : "))
		if ch!=1 and ch!=2:
			print("No such option")
			exit(1)
	firefox_path = get_browser_path('firefox')
	profiles = [i for i in os.listdir(firefox_path) if i.endswith('.default')]
	sqlite_path = firefox_path+ profiles[0]+'/places.sqlite'
	if os.path.exists(sqlite_path):
		firefox_connection = sqlite3.connect(sqlite_path)
		ff_cursor = firefox_connection.cursor()
		#print("connection successful")
		#clearing history in firefox
		try:
			if ch == 1:
				s = raw_input("Enter the list of words separated by space: ")
				unwanted_names = s.split(' ')
				clear_history_by_names(unwanted_names , ff_cursor , test)
				print("Done..........")
			else:
				print("To delete history by time: Enter the starting hour from which u want to start deleting the history")
				print("then enter the ending hour")
				print("Ex: If you want to delete history not older than 6 hours and not newer than 4 hours then starting hour = 6 and ending hour = 4")
				starting_time = int(input("Enter the starting hour: "))
				ending_time = int(input("Enter the ending time: "))
				clear_history_by_time(starting_time , ending_time , ff_cursor , test)
				print("Done.........")
			firefox_connection.commit()
			ff_cursor.close()
		except Exception as err:
			print(err)
	else:
		print("Firefox browser not found")

    
