#!/usr/bin/python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Wrapper to list and handle system services
"""

import argparse
import os

from plinth import cfg
from plinth.modules.i2p.helpers import RouterEditor, TunnelEditor

cfg.read()
module_config_path = os.path.join(cfg.config_dir, 'modules-enabled')

I2P_CONF_DIR = '/var/lib/i2p/i2p-config'


def parse_arguments():
    """Return parsed command line arguments as dictionary."""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')

    subparser = subparsers.add_parser(
        'add-favorite', help='Add an eepsite to the list of favorites')
    subparser.add_argument('--name', help='Name of the entry', required=True)
    subparser.add_argument('--url', help='URL of the entry', required=True)
    subparser.add_argument('--description', help='Short description',
                           required=False)
    subparser.add_argument('--icon', help='URL to icon', required=False)

    subparser = subparsers.add_parser('set-tunnel-property',
                                      help='Modify configuration of a tunnel')
    subparser.add_argument('--name', help='Name of the tunnel', required=True)
    subparser.add_argument('--property', help='Property to modify',
                           required=True)
    subparser.add_argument('--value', help='Value to assign', required=True)

    subparsers.required = True
    return parser.parse_args()


def subcommand_set_tunnel_property(arguments):
    """Modify the configuration file for a certain tunnel."""
    editor = TunnelEditor()
    editor \
        .read_conf() \
        .set_tunnel_idx(arguments.name) \
        .set_tunnel_prop(arguments.property, arguments.value) \
        .write_conf()
    print('Updated "{property}" of {filename} to {value}'.format(
        property=editor.calc_prop_path(arguments.property),
        filename=editor.conf_filename, value=arguments.value))


def subcommand_add_favorite(arguments):
    """
    Adds a favorite to the router.config

    :param arguments:
    :type arguments:
    """
    url = arguments.url

    editor = RouterEditor()
    editor.read_conf().add_favorite(arguments.name, url, arguments.description,
                                    arguments.icon).write_conf()

    print('Added {} to favorites'.format(url))


def main():
    """Parse arguments and perform all duties."""
    arguments = parse_arguments()

    subcommand = arguments.subcommand.replace('-', '_')
    subcommand_method = globals()['subcommand_' + subcommand]
    subcommand_method(arguments)


if __name__ == '__main__':
    main()
