"""
MIT License

Copyright (c) 2021 Connor Runyan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import logging
import re
import subprocess

from typing import Dict
from subprocess import check_output

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


class PlayerAction:
    LOG_IN = "LOG_IN"
    LOG_OUT = "LOG_OUT"
    ONLINE = "ONLINE"


def get_server_info():
    ip_cmd = ["hostname", "-I"]
    try:
        results = str(check_output(ip_cmd)).split()
        logger.info(results)
        if results:
            pub_ip = results[0].replace("'", "").replace("b", "")
        msg = f"Server IP/port: {pub_ip}:2456"
        return msg
    except subprocess.CalledProcessError:
        return "Could not get server IP/port..."


def get_server_status():
    cmd = ["systemctl", "status", "valheimserver.service"]
    cmd_output = str(check_output(cmd)).strip()
    result = re.search(r"Active:(.* ago)", cmd_output)
    if result:
        return result.group(1)
    return "Something went wrong... Unable to fetch status."


def get_active_players(log_path: str) -> Dict[str, str]:
    """Parses the given system log and returns a name and log-in date/time of online players.

    Args:
        log_path (str): Full path to the log file. This is the log output from your Valheim server.

    Returns:
        Dict[str, str]: Dictionary of information about each player currently online.
    """
    with open(log_path) as IFH:
        log_data = IFH.read()
    logged_in_events = get_player_events(
        log_contents=log_data, action_type=PlayerAction.LOG_IN
    )
    logged_out_events = get_player_events(
        log_contents=log_data, action_type=PlayerAction.LOG_OUT
    )
    # Want all the players who have logged in, and do not have an associated logged out event
    active_player_ids = logged_in_events.keys() - logged_out_events.keys()
    active_players = dict(
        filter(lambda pair: pair[0] in active_player_ids, logged_in_events.items())
    )
    return {
        conn_id: _create_player_activity_info(p_vals, PlayerAction.ONLINE)
        for conn_id, p_vals in active_players.items()
    }


def format_active_player_message(active_players: Dict[str, str]) -> str:
    message = ["Name, Logged-in:"]
    for conn_id, player in active_players.items():
        message.append(f"{player.get('username')},{player.get('timestamp')} UTC")
    return "\n".join(message)


def get_player_events(
    log_contents: str, action_type: PlayerAction
) -> Dict[str, Dict[str, str]]:
    """Parses a log generated by the Valheim server and supplies login events.

    Args:
        log_contents (str): Containing all the contents of the Valheim server syslog.
        action_type (PlayerAction): Type of event to look for in the log (i.e. Login or Logout).

    Returns:
        Dict[str, str]: Key value pairs of format {"connect_id": {"username": "", "timestamp": ""}}.
    """
    re_event_pattern = None
    if action_type == PlayerAction.LOG_IN:
        re_event_pattern = re.compile(
            r"(?P<timestamp>\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}).*Got character ZDOID from (?P<username>\w+) : (?P<connect_id>\d+):1"
        )
    elif action_type == PlayerAction.LOG_OUT:
        re_event_pattern = re.compile(
            r"(?P<timestamp>\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}).*Destroying abandoned non persistent zdo (?P<connect_id>\d+):"
        )
    else:
        raise ValueError(
            f"Unsupported player action '{action_type}'. Did you forget to implement a match matter for this?"
        )

    events_found = [l.groupdict() for l in re_event_pattern.finditer(log_contents)]
    if events_found:
        return {
            event.get("connect_id", ""): _create_player_activity_info(
                event, action_type
            )
            for event in events_found
        }
    return dict()


def _create_player_activity_info(
    found_results: Dict[str, str], action: PlayerAction
) -> Dict[str, str]:
    return {
        "username": found_results.get("username", ""),
        "timestamp": found_results.get("timestamp", ""),
        "action": action,
    }


def get_logout_events(log_contents: str) -> Dict[str, str]:
    pass