import random
import time
import logging
from mainserver.server import Server

# try:
#     from urllib.parse import urlparse, urljoin
# except ImportError:
#     from urlparse import urlparse

logging.basicConfig(level=logging.INFO)
_logger = logging.getLogger('opcua')

if __name__ == '__main__':
    # setup our server
    server = Server()
    print("Server configured")
    server.start()
    server.set_endpoint('opc.tcp://localhost:4841/opcua/')
    print("Server Started")
    idx = server.register_namespace("mynamespace")
    # populating our address space
    # server.nodes, contains links to very common nodes like objects and root
    obj_vplc = server.nodes.objects.add_object(idx, 'vPLC')
    var_temperature = obj_vplc.add_variable(idx, 'temperature', 0)
    var_pressure = obj_vplc.add_variable(idx, 'pressure', 0)
    var_pumpsetting = obj_vplc.add_variable(idx, 'pumpsetting', 0)
    # _logger.info("starting server...")
    server.start()
    # run forever every 5 secs
    try:
        # def update_value():
        while True:
            # Writing Variables
            var_temperature.set_value(random.randint(25, 35))
            var_pressure.set_value(random.randint(55, 75))
            var_pumpsetting.set_value(random.randint(0, 1))
            time.sleep(5)
        # sub = server.create_subscription(1, update_value())
        # sub.subscribe_data_change(var_temperature)
    finally:
        server.stop()
