import asyncio

from smartcard.util import toBytes, toHexString

from scProcessor import sCard


async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '10.192.1.134', 21077)

    print(f'Send: {message!r}')
    writer.write(message.encode())

    data = await reader.read(100)
    print(f'Received: {data.decode()!r}')

    print('Close the connection')
    writer.close()


class EchoClientProtocol(asyncio.Protocol):
    def __init__(self, message, loop):
        self.message = message
        self.loop = loop
        self.transport = None
        # init sCard
        self.obj = sCard()

    def connection_made(self, transport):
        self.transport = transport
        # transport.write(self.message.encode())
        # print('Data sent: {!r}'.format(self.message))

        # Read ICC file
        icc = self.obj.readBinaryEF()

        # just test to send to wialon
        self.send_to_serverSerial(icc)

    def data_received(self, data):
        # print('Data received: {!r}'.format(data.decode()))
        print('Data received:', data)
        parser = bytearray(data)
        if parser[0] == 0x40 and parser[1] == 0x40:
            print('heaer of tacho catd')
        else:
            return

        # get atr 4040 0001 01
        if parser[4] == 0x01:
            # Need to request atr from sCard
            atr = self.obj.getAtr()
            print('ATR:', type(atr), atr)
            self.send_to_server(atr, 1)
        elif parser[4] == 2:
            # # it is APDU from device
            # 4040 0008 02 B4144B26E9D7F0
            # B4144B26E9D7F0 | DECODED: 00 00 02 0C 02 A4 02

            apdu_from_device = data[5:]
            print('apdu_from_device:', type(apdu_from_device), apdu_from_device)

        # print('test', hex(test[0]), test[1])
        # print('Send: {!r}'.format(message))
        # self.transport.write(data)

    def connection_lost(self, exc):
        print('The server closed the connection')
        print('Stop the event loop')
        self.loop.stop()

    def send_to_serverSerial(self, data):
        # byteData = bytearray(data)
        # print('test', hex(test[0]), test[1])
        # print('Send: {!r}'.format(message))
        # tachograph card header 2424 000A 01 00 0047063B06170469
        tch = [0x24, 0x24, 0x00, 0x0A, 0x01, 0x00]
        apdu = tch + data
        self.transport.write(bytearray(apdu))

    def send_to_server(self, data, cmd_type):
        # cmd_type - (ATR - 1, APDU - 2)

        print('Sending data to server: ', type(data), data)
        # print('test', hex(test[0]), test[1])

        # tachograph card header 2424 000A 01 00 0047063B06170469
        # header for tacho card

        tch = [0x24, 0x24, 0x00, len(data), 0x01, cmd_type]
        # compose apdu with header
        apdu = tch + data
        self.transport.write(bytearray(apdu))

# loop = asyncio.get_event_loop()
# message = 'Hello World!'
# coro = loop.create_connection(lambda: EchoClientProtocol(message, loop), '10.192.1.134', 21077)
# loop.run_until_complete(coro)
# loop.run_forever()
# loop.close()