"""
Project: Extending the Multi-Clipboard
Page 229
"""

import sys
import shelve
import pyperclip
from pathlib import Path


def help():
    script = Path(__file__).name
    print(
        f"""
    {script} saves and loads pieces of text to the clipboard.
    Usage:  python {script} save <key>    Saves clipboard to keyword
            python {script} <key>         Loads keyword to clipboard
            python {script} list          Loads all keywords to clipboard
            python {script} delete <key>  Deletes keyword
            python {script} wipe          Deletes all keywords
            python {script} help          Prints this help
    """.strip()
    )


def save(key, data):
    if key in data.keys():
        print(f"ERROR: '{key}' ya existe")
        sys.exit(1)
    else:
        data[key] = pyperclip.paste()


def delete(key, data):
    if key in data.keys():
        print(f"INFO: '{key}' se ha eliminado")
        del data[key]
    else:
        print(f"ERROR: '{key}' no existe")
        sys.exit(1)


def get(key, data):
    if key in data.keys():
        pyperclip.copy(data[key])
    else:
        print(f"ERROR: '{key}' no existe")
        sys.exit(1)


def ls(data):
    for key, val in data.items():
        txt = val.strip().split("\n")[0]
        if len(txt) > 100:
            txt = f"{txt[:97]}..."
        print(f"{key} -> {txt}")


def wipe(data):
    for key in data.keys():
        delete(key, data)


data = shelve.open("mcb")

if len(sys.argv) == 1:
    print("ERROR: al menos un argumento es necesario")
    sys.exit(1)

match sys.argv[1]:
    case "save" | "delete":
        if len(sys.argv) == 2:
            print("ERROR: una palabra clave es necesaria")
            sys.exit(1)
        for key in sys.argv[2:]:
            if sys.argv[1] == "save":
                save(key, data)
            else:
                delete(key, data)
    case "list":
        ls(data)
    case "wipe":
        wipe(data)
    case "help":
        help()
    case key:
        get(key, data)

data.close()
