name = "aidb"

import os, sqlite3
from datetime import datetime

import appdirs # ToDo - can I delete this as it is only used in config?
from peewee import *
from playhouse.dataset import DataSet

# Assumes that `pydatasci.create_config()` has been run during installation instructions:
from pydatasci import get_config


def get_path_db():
	pds_config = get_config()
	if pds_config is None:
		print("\n Welcome - Your configuration has not been set up. Please run `pds.create_config()` in Python shell.\n")
	else:
		db_path = pds_config['db_path']
	return db_path


def get_db():
	path = get_path_db()
	# peewee ORM connection to database:
	db = SqliteDatabase(path)
	return db


def get_path_dataset_ext():
	path = get_path_db()
	prefix = "sqlite:///"
	prefix_db_path = prefix + path
	return prefix_db_path


def get_dataset_ext():
	# http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#dataset
	path = get_path_dataset_ext()
	db = DataSet(path)
	return db


def create_db():
	# ToDo - Could let the user specify their own db name, for import tutorials.
	db_path = get_path_db()
	db_exists = os.path.exists(db_path)
	if db_exists:
		print("\n=> Skipping database file creation as a database file already exists at path:\n" + db_path + "\n")
	else:
		# Create sqlite file for db.
		try:
			db = get_db()
		except:
			print("\n=> Error - failed to create database file at path:\n" + db_path)
			print("===================================\n")
			raise
		print("\n=> Success - created database file for machine learning metrics at path:\n" + db_path + "\n")

	db = get_db()
	# Create tables inside db.
	tables = db.get_tables()
	table_count = len(tables)
	if table_count > 0:
		print("\n=> Warning - skipping table creation as the following tables already exist:\n" + str(tables) + "\n")
	else:
		db.create_tables([Job])
		tables = db.get_tables()
		table_count = len(tables)
		if table_count > 0:
			print("\n=> Success - created the following tables within database:\n" + str(tables) + "\n")
		else:
			print("\n=> Error - failed to create tables. Please see README file section titled: 'Deleting & Recreating the Database'\n")


def delete_db(confirm:bool=False):
	if confirm:
		db_path = get_path_db()
		db_exists = os.path.exists(db_path)
		if db_exists:
			try:
				os.remove(db_path)
			except:
				print("\n=> Error - failed to delete database file at path:\n" + db_path)
				print("===================================")
				raise
			print("\n=> Success - deleted database file at path:\n" + db_path + "\n")

		else:
			print("\n=> Warning - there is no file to delete at path:\n" + db_path + "\n")
	else:
		print("\n=> Warning - skipping deletion because `confirm` arg not set to boolean `True`.\n")


# peewee ORM:
class BaseModel(Model):
    class Meta:
        database = get_db()


class Job(BaseModel):
    title = CharField()
