import os
import sys
import platform
import argparse

from . import cli
from . import udev
from . import devices
from . import get_first_mouse


_EPILOG = """
Please report any bug on Github: https://github.com/flozz/rivalcfg/issues
"""


def _check_linux():
    """Run some checks on Linux."""

    # Only run checks on Linux
    if platform.system() != "Linux":
        return

    # Skip check for root as there will be no issue for this user
    if os.getuid() == 0:
        return

    # Skip check if user is trying to update udev rules:
    if "--update-udev" in sys.argv:
        return

    if not os.path.isfile(udev.RULES_FILE_PATH):
        print("W: udev rules are not installed. You may not be able to open the device using a regular user.")  # noqa
        print("\n   Run 'rivalcfg --update-udev' as root to fix.\n")
    elif not udev.is_rules_file_up_to_date():
        print("W: Installed udev rules were generated by an other rivalcfg version.")  # noqa
        print("\n   Run 'rivalcfg --update-udev' as root to update.\n")


def main(args=sys.argv[1:]):
    # On Linux: check udev rules
    _check_linux()

    # Try to open a mouse
    mouse = get_first_mouse()

    cli_parser = argparse.ArgumentParser(
            prog="rivalcfg",
            epilog=_EPILOG)
    cli.add_main_cli(cli_parser)

    if mouse:
        mouse_profile = devices.get_profile(
                vendor_id=mouse.vendor_id,
                product_id=mouse.product_id)
        cli.add_mouse_cli(cli_parser, mouse_profile)

    settings = cli_parser.parse_args(args)

    # Reset
    if mouse and settings.RESET:
        mouse.reset_settings()

    # Apply settings
    if mouse:
        for setting_name, value in [
                (k.lower(), v) for k, v in vars(settings).items()]:
            if value is None:
                continue
            method_name = "set_%s" % setting_name
            if not hasattr(mouse, method_name):
                continue
            getattr(mouse, method_name)(value)

        # Save settings in the internal device memory
        if settings.SAVE:
            mouse.save()


if __name__ == "__main__":
    main()
