"""
run speedtest-cli on every computer in mesh
"""
import datetime
import os
import re
import time
import asyncio, asyncssh, sys
import paramiko
import subprocess
import json
from cowmesh_helpers import cleanup_iperf_server

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
SECRETS_PATH = os.path.join(PROJECT_PATH, "secrets.json")
with open(SECRETS_PATH, 'r') as f:
    SECRETS = json.loads(f.read())

base_node = "janastunuc"  # nuc in jaaga

nodes = [
    "janastunuc",   # nuc in jaaga
    "solipi",       # pi in guard
    "writer",       # pi in new-gazebo
]


class CowmeshPiSpeedtestTester:

    def __init__(self, log=None, debug=False):
        if log:
            self.log = log
        self.debug = debug
        self.results = {}

    async def log(self, msg):
        print(msg)

    async def debug_log(self, msg):
        if self.debug:
            await self.log(msg)

    async def speedtest_node(self, node):
        await self.log("++ running speedtest on {}".format(node))
        user = SECRETS["HOST_INFO"][node]["user"]
        password = SECRETS["HOST_INFO"][node]["password"]

        myconn = paramiko.SSHClient()
        myconn.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ip = SECRETS["HOST_INFO"][node]["ip"]
        myconn.connect(ip, username=user, password=password)

        remote_cmd = 'speedtest-cli --simple'
        (stdin, stdout, stderr) = myconn.exec_command(remote_cmd)
        output = str(stdout.read())
        await self.debug_log("output: {}".format(output))
        await self.debug_log("errors: {}".format(stderr.read()))
        myconn.close()

        return output

    async def run_test(self):

        for node in nodes:
            result_key = "{}".format(node)
            try:
                r = await self.speedtest_node(node)
                self.results[result_key] = r
            except Exception as e:
                try:
                    self.log("error: {}".format(e))
                except:
                    continue
                self.results[result_key] = "error: {}".format(e)

    async def output_results(self):
        results_str = ""
        now = datetime.datetime.now()
        date = now.date()
        time = now.time()
        results_str += "**** computer speedtests on {date:%m-%d-%Y} at {time:%H:%M}:\n\n".format(date=date, time=time)
        for test_name, result in self.results.items():
            result = str(result)
            result = result.replace("b'", "")
            result = result.replace("'", "")
            result = result.replace("\\n", " | ")
            results_str += "{}: {}\n".format(test_name, result)
        await self.log(results_str)


if __name__ == "__main__":
    try:
        tester = CowmeshPiSpeedtestTester()

        async def main_fun():
            await tester.run_test()
            await tester.output_results()

        asyncio.get_event_loop().run_until_complete(main_fun())


    except (OSError, asyncssh.Error) as exc:
        sys.exit('SSH connection failed: ' + str(exc))