#!/usr/bin/env python3


import sqlite3
from sqlite3 import Error




class db:

    def __init__(self, dbFile):
        self.dbFile = r'"'+dbFile+'"'

        sql_create_new_articles = """ CREATE TABLE IF NOT EXISTS new_articles (
                                            id integer PRIMARY KEY,
                                            hash text NOT NULL,
                                            title text NOT NULL,
                                            siteId integer NOT NULL
                                        ); """

        sql_create_articles = """ CREATE TABLE IF NOT EXISTS articles (
                                            id integer PRIMARY KEY,
                                            hash text NOT NULL,
                                            date text,
                                            title text,
                                            siteId integer NOT NULL,
                                            lnk text,
                                            href text
                                        ); """

        sql_create_article_types = """ CREATE TABLE IF NOT EXISTS article_types (
                                            id integer PRIMARY KEY,
                                            type text NOT NULL,
                                            article_id integer NOT NULL,
                                            FOREIGN KEY (article_id) REFERENCES articles (id)
                                        ); """


        sql_create_article_companies = """ CREATE TABLE IF NOT EXISTS article_companies (
                                            id integer PRIMARY KEY,
                                            name text NOT NULL,
                                            article_id integer NOT NULL,
                                            FOREIGN KEY (article_id) REFERENCES articles (id)
                                        ); """
        

        sql_create_article_contents = """ CREATE TABLE IF NOT EXISTS article_contents (
                                            id integer PRIMARY KEY,
                                            place text NOT NULL,
                                            start text,
                                            desc text,
                                            lnk text,
                                            contact text,
                                            article_id integer NOT NULL,
                                            FOREIGN KEY (article_id) REFERENCES articles (id)
                                        ); """


        # create a database connection
        conn = create_connection(dbFile)

        # create tables
        if conn is not None:
            # create projects table
            create_table(conn, sql_create_new_articles)
            create_table(conn, sql_create_articles)
            create_table(conn, sql_create_article_types)
            create_table(conn, sql_create_article_companies)
            create_table(conn, sql_create_article_contents)

        else:
            print("Error! cannot create the database connection.")
        
        self.conn = conn


    def write(self, articleObj):
        with self.conn:
            
            #hash, date, ,title, siteId, lnk, href
            article = (articleObj['id'], articleObj['Alter'], articleObj['Titel'], articleObj['siId'], articleObj['lnk'], articleObj['href']);
            article_id = create_articles(self.conn, article)

            type = (articleObj['Anstellungsart'], article_id);
            create_article_types(self.conn, type)

            company = (articleObj['Firma'], article_id);
            create_article_companies(self.conn, company)

            if articleObj['content'] == "none":
                content = ("none", "none", "none", "none", "none", article_id);
            else:
                content = (articleObj['content']['Ort'], articleObj['content']['Antritt'], articleObj['content']['Beschreibung'], articleObj['content']['Anmelden'], articleObj['content']['Kontaktperson'], article_id);
            create_article_contents(self.conn, content)

    def writeNew(self, articleObj):
        with self.conn:
            article = (articleObj['id'], articleObj['Titel'], articleObj['siId']);
            create_new_articles(self.conn, article)

    def readAll(self, table):
        with self.conn:
            cur = self.conn.cursor()
            cur.execute("SELECT * FROM " + table)
            rows = cur.fetchall()
            return rows
    

    def readTables(self):
        with self.conn:
            cur = self.conn.cursor()
            cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
            rows = cur.fetchall()
            return rows

    def delete_table(self, table):
        with self.conn:
            sql = 'DELETE FROM ' + table
            cur = self.conn.cursor()
            cur.execute(sql)
            self.conn.commit()
            





def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)

    return conn


def create_table(conn, create_table_sql):
    """ create a table from the create_table_sql statement
    :param conn: Connection object
    :param create_table_sql: a CREATE TABLE statement
    :return:
    """
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)




def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)

    return conn


def create_new_articles(conn, article):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = ''' INSERT INTO new_articles(hash, title, siteId)
              VALUES(?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, article)
    conn.commit()
    return cur.lastrowid

def create_articles(conn, article):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = ''' INSERT INTO articles(hash, date, title, siteId, lnk, href)
              VALUES(?,?,?,?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, article)
    conn.commit()
    return cur.lastrowid

def create_article_companies(conn, name):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = ''' INSERT INTO article_companies(name, article_id)
              VALUES(?,?) '''
    cur = conn.cursor()
    cur.execute(sql, name)
    conn.commit()
    return cur.lastrowid

def create_article_types(conn, type):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = ''' INSERT INTO article_types(type, article_id)
              VALUES(?,?) '''
    cur = conn.cursor()
    cur.execute(sql, type)
    conn.commit()
    return cur.lastrowid

def create_article_contents(conn, content):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = ''' INSERT INTO article_contents(place, start, desc, lnk, contact, article_id)
              VALUES(?,?,?,?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, content)
    conn.commit()
    return cur.lastrowid


