#!/usr/bin/env python3

import logging
import mitel_ommclient2
import time

logger = logging.getLogger("fieldpoc.dect")

class Dect:
    def __init__(self, fp):
        self.fp = fp

    def _init_client(self):
        self.c = mitel_ommclient2.OMMClient2(
            host=self.fp.config.dect.host,
            username=self.fp.config.dect.username,
            password=self.fp.config.dect.password,
            ommsync=True,
        )

    def get_temp_number(self):
        temp_num_prefix = next(self.fp.extensions.extensions_by_type("temp")).num
        current_temp_extension = 0
        used_temp_extensions = [u.num[len(temp_num_prefix):] for u in self.c.find_users(lambda u: u.num.startswith(temp_num_prefix))]

        while "{:0>4}".format(current_temp_extension) in used_temp_extensions:
            current_temp_extension += 1

        return "{}{:0>4}".format(temp_num_prefix, current_temp_extension)

    def get_sip_password_for_number(self, num):
        return num


    def run(self):
        logger.info("initialising connection to OMM")
        self._init_client()

        while True:
            msg = self.fp.queues["dect"].get()
            self.fp.queues["dect"].task_done()

            if msg.get("type") == "stop":
                break
            elif msg.get("type") == "sync":
                unbound_devices = self.c.find_devices(lambda d: d.relType == mitel_ommclient2.types.PPRelTypeType("Unbound"))

                for d in unbound_devices:
                    print(d)
                    temp_num = self.get_temp_number()
                    u = self.c.create_user(temp_num)
                    print(u)
                    self.c.attach_user_device(u.uid, d.ppn)
                    self.c.set_user_relation_fixed(u.uid)
                    self.c.set_user_sipauth(u.uid, temp_num, self.get_sip_password_for_number(temp_num))