#!/usr/bin/env python3
from typing import Optional
from argparse import ArgumentParser
from enum import Enum

from home.config import config
from home.mqtt import MqttRelay
from home.mqtt.esp import MqttEspBase
from home.mqtt.temphum import MqttTempHum
from home.mqtt.esp import MqttEspDevice

mqtt_client: Optional[MqttEspBase] = None


class NodeType(Enum):
    RELAY = 'relay'
    TEMPHUM = 'temphum'


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--device-id', type=str, required=True)
    parser.add_argument('--type', type=str, required=True,
                        choices=[i.name.lower() for i in NodeType])

    config.load('mqtt_util', parser=parser)
    arg = parser.parse_args()

    mqtt_node_type = NodeType(arg.type)
    devices = MqttEspDevice(id=arg.device_id)

    if mqtt_node_type == NodeType.RELAY:
        mqtt_client = MqttRelay(devices=devices)
    elif mqtt_node_type == NodeType.TEMPHUM:
        mqtt_client = MqttTempHum(devices=devices)

    mqtt_client.set_message_callback(lambda device_id, payload: print(payload))
    mqtt_client.configure_tls()
    try:
        mqtt_client.connect_and_loop()
    except KeyboardInterrupt:
        mqtt_client.disconnect()
