#!/usr/bin/env python3
# coding: utf-8

# created: 05.05.20

"""
Welcome to the 'luechenbresse' module initialization script.

Usage:
    luechenbresse [--info] [--init] [--dir DIR] [--get FEED] [--get_all]
    luechenbresse --version
    luechenbresse (-h | --help)

Options
    -h --help           Show this screen
    --version           print program version
    --tatsch            produces a file in the scripts current working directory (test only)
    --info              print some info about environment
    --args              print parsed command line arguments (test only)
    --init              initialize local structures in ~/.luechenbresse
    --dir DIR           folder for the database files, relative to CWD, you better use ~/...
                        if not specified, ~/.luechenbresse will be used
                        caveat: existing settings will be overwritten when specified
    --get FEED          gets a certain feed from the internet
    --get_all           gets all feeds from the internet

The optional "--dir" command line argument is only used when "--init" is also specified.
All housekeeping commands use the database folder specified in ~/.luechenbresse/luechenbresse.ini.
"""

import sys
import os
from time import time
import json
from pathlib import Path
import configparser
import tracemalloc
import sqlite3
import logging
import logging.handlers

from docopt import docopt

from luechenbresse import __version__ as luechenbresse_version      # TODO gefällt mir nicht
from luechenbresse import data
from luechenbresse import feed      # TODO change to from luechenbresse.feed import Feed
from luechenbresse import ini
from luechenbresse.mailgun import Mailgun
from luechenbresse.dotfolder import LogManager, init_dotfolder

# cwd ist der Aufrufort (Skript muss nicht ausführbar i.S.v. `chmod u+x` sein)
# Files aus der Distribution können über die `__files__` Variable navogiert werden.

def info(args):
    logging.info("I am", os.environ['_'])
    logging.info(f"Running under {sys.executable} ({sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro})")
    logging.info(f"Current Working Directory: {os.getcwd()}")
    logging.info(f"__file__ = {__file__}")
    feeds = data.feeds()
    logging.info(f"feeds: {type(feeds)}, {json.dumps(feeds)}")
    Mailgun().shoot("luechenbresse --info", "Hey there.")



if __name__ == "__main__":
    tracemalloc.start()
    t0 = time()
    LogManager()

    logging.info("Willkommen bei der Luechenbresse.")
    logging.info(f"module version: {luechenbresse_version}")    # TODO gefällt mir nicht

    try:
        arguments = docopt(__doc__, version='Luechenbresse 0.0.4')
        logging.info(f"cli: {json.dumps(arguments)}")
        done = False

        if arguments["--info"]:
            info(arguments)
            raise SystemExit(0)
    #        done = True

        if arguments["--init"]:
            init_dotfolder(arguments["--dir"])
            done = True

        if arguments["--get"]:
           feed.process_feed(arguments["--get"])
        done = True

        if arguments["--get_all"]:
            feed.process_all_feeds()
            done = True

        if not done:
            logging.warning("Was wolltest Du denn?")

        logging.info("Time total: %0.1fs" % (time() - t0))
        current, peak = tracemalloc.get_traced_memory()
        logging.info("Memory: current = %0.1f MB, peak = %0.1f MB" % (current / 1024.0 / 1024, peak / 1024.0 / 1024))
    except KeyboardInterrupt:
        logging.warning("caught KeyboardInterrupt")
    except Exception as ex:
        logging.exception("Sorry.")
    LogManager().mail()
    logging.info("Ciao.")