"""
Fake Mikrotik API Client for testing and for reading recorded commands.
"""
from .mikrotik import MikrotikApiClient
import yaml


class FakeMikrotikApiClient(MikrotikApiClient):

    def __init__(self,
                 host,
                 username,
                 password,
                 enable_ssl=False,
                 port=None,
                 timeout=30,
                 ignore_permissions=False,
                 ignore_internal_errors=False,
                 record=False):
        self.commands = []  # set to [[words], [results]]
        super().__init__('TEST',
                         username,
                         password,
                         ignore_permissions=ignore_permissions,
                         ignore_internal_errors=ignore_internal_errors)
        infile = host
        if infile:
            with open(infile) as f:
                self.commands = yaml.safe_load(f.read())['commands']
        self._cmd = None
        self._buf = None

    async def connect(self):
        pass

    async def read(self):
        if not self._buf:
            try:
                self._buf = self.commands.pop([x[0] for x in self.commands
                                               ].index(self._cmd))[1]
            except ValueError:
                # if we didn't capture this command, just return empty result
                return ['!done']
        return self._buf.pop(0)

    async def write(self, words):
        self._cmd = words
