#!python

# `getitdone` to-do list application
#
#     Copyright (C) 2020  Ryan Butler
#
#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.
#
#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.
import sqlite3
from os import mkdir
from pathlib import Path
from sqlite3 import Error
from sys import argv


def insert_db(taskName: str):
    """Insert new task into database.

    Args:
        taskName (str): Name of task.
    """
    query = f"""
        INSERT INTO
        tasks (name)
        VALUES
        ('{taskName}')
    """
    execute_query(connection, query)
    print(f"'{taskName}' added to list")


def update_db(taskName: str, newName: str):
    """Update task in database.

    Args:
        taskName (str): Current name of task.
        newName (str): New name of task.
    """
    userInput = input(f"Update '{taskName}' with '{newName}'? Y/N ")
    if userInput.lower() == "y":
        query = f"""
            UPDATE tasks
            SET name = '{newName}'
            WHERE name = '{taskName}'
        """
        execute_query(connection, query)
        print(f"'{taskName}' updated to `{newName}`")


def delete_db(taskName: str):
    """Delete task from database.

    Args:
        taskName (str): Task name to be deleted.
    """
    userInput = input(f"Delete '{taskName}' from your list? Y/N ")
    if userInput.lower() == "y":
        query = f"DELETE FROM tasks WHERE name = '{taskName}'"
        execute_query(connection, query)
        print(f"'{taskName}' deleted")


def list_tasks():
    """List all tasks in database."""
    query = "SELECT * FROM tasks"
    response = execute_read_query(connection, query)
    print("\n### get-it-done ###\n\n" "-----------------")
    if len(response) < 1:
        print("...No tasks...")
    else:
        for task in response:
            print(f"{task[0]} - {task[1]}")
    print("-----------------\n")


def command_help():
    """Print help with available list of commands and arguments."""
    print("\n### get-it-done ###\n")
    print(
        "OPTIONS\n"
        "\t`--new` or `-n` '<task-name>'\n"
        "\t\tCreate a new task with name in first argument\n\n"
        "\t`--update` or `-u` '<task-name>' '<new-name>'\n"
        "\t\tUpdate task in first argument with value of second argument\n\n"
        "\t`--delete` or `-d` '<task-name>'\n"
        "\t\tDelete task in first argument with value of second argument\n\n"
        "\t`--list` or `-l`\n"
        "\t\tList all tasks\n\n"
        "\t`--help` or `-h`\n"
        "\t\tShows man page for todolist\n"
    )


def create_connection(path: str) -> object:
    """Create connection with database.

    Args:
        path (str): Path to the database.

    Returns:
        [type]: [description]
    """
    connection = None
    try:
        connection = sqlite3.connect(path)
    except Error as e:
        print(f"The error '{e}' occurred")
    return connection


def execute_query(connection: object, query: str):
    """Execute SQL write query with connection to database and commit the write.

    Args:
        connection (object): Database connection
        query (str): SQL query
    """
    cursor = connection.cursor()
    try:
        cursor.execute(query)
        connection.commit()
    except Error as e:
        print(f"The error '{e}' occurred")


def execute_read_query(connection: object, query: str) -> object:
    """Execute SQL read query with connection to the database.

    Args:
        connection (object): Database connection
        query (str): SQL query

    Returns:
        object: Result object from database
    """
    cursor = connection.cursor()
    result = None
    try:
        cursor.execute(query)
        result = cursor.fetchall()
        return result
    except Error as e:
        print(f"The error '{e}' occurred")


if __name__ == "__main__":
    home = str(Path.home())
    createTable = """
    CREATE TABLE IF NOT EXISTS tasks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL
    );
    """
    try:
        mkdir(f"{home}/.getitdone")
    except FileExistsError:
        pass
    connection = create_connection(f"{home}/.getitdone/getitdone_db.sqlite")
    execute_query(connection, createTable)

    action = argv[1].lower()
    try:
        if action == "--new" or action == "-n":
            taskName = argv[2]
            insert_db(taskName)
        elif argv[1] == "--update" or argv[1] == "-u":
            taskName = argv[2]
            newName = argv[3]
            update_db(taskName, newName)
        elif argv[1] == "--delete" or argv[1] == "-d":
            taskName = argv[2]
            delete_db(taskName)
        elif argv[1] == "--list" or argv[1] == "-l":
            list_tasks()
        elif argv[1] == "--help" or argv[1] == "-h":
            command_help()
        else:
            print("Please refer to help (`--help` or `-h`) for instructions\n")
    except IndexError:
        print("Please refer to help (`--help` or `-h`) for instructions\n")
