#!/usr/local/bin/python
# -*- coding: utf-8 -*-

"""
Created on Sep 17, 2020

@author: Carima
"""
# from SimpleXMLRPCServer import SimpleXMLRPCServer, resolve_dotted_attribute
# from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
from xmlrpc.server import SimpleXMLRPCServer, resolve_dotted_attribute
from xmlrpc.server import SimpleXMLRPCRequestHandler
from printThread import printThread
from printThread_4k import printThread_4k
from printThread_kist import printThread_Kist
from printThread_Shofu import printThread_Shofu

import logging
import logging.handlers
from logging.handlers import TimedRotatingFileHandler
from configparser import ConfigParser
import os
import string

if __name__ == '__main__':
    logger = logging.getLogger('dp110server')
    hdlr = logging.handlers.TimedRotatingFileHandler('./xmlrpc_server.log', when="d", interval=30, backupCount=3)
    formatter = logging.Formatter('%(funcName)s %(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)


    # Restrict to a particular path.
    class RequestHandler(SimpleXMLRPCRequestHandler):
        """
        http://code.activestate.com/recipes/496700-logging-simplexmlrpcserver/
        """

        def do_POST(self):
            clientIP, port = self.client_address
            # Log client IP and Port
            logger.info('Client IP: %s - Port: %s' % (clientIP, port))
            try:
                # get arguments
                data = self.rfile.read(int(self.headers["content-length"]))
                # Log client request
                # if data.find('%') > 5:
                #   logger.info('Client request: uploadfile')
                # else:
                logger.info('Client request: \n%s\n' % data)

                response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
                )
                # Log server response
                logger.info('Server response: \n%s\n' % response)

            except:  # This should only happen if the module is buggy
                # internal error, report as HTTP server error
                logger.info('do_post except error')
                self.send_response(500)
                self.end_headers()
            else:
                # got a valid XML RPC response
                self.send_response(200)
                self.send_header("Content-type", "text/xml")
                self.send_header("Content-length", str(len(response)))
                self.end_headers()
                self.wfile.write(response)
                logger.info('do_post sucecss responese')
                # shut down the connection
                self.wfile.flush()
                self.connection.shutdown(1)

        rpc_paths = ('/RPC2',)


    class MySimpleXMLRPCServer(SimpleXMLRPCServer):
        def _dispatch(self, method, params):
            func = None
            try:
                # check to see if a matching function has been registered
                func = self.funcs[method]
            except KeyError:
                if self.instance is not None:
                    # check for a _dispatch method
                    if hasattr(self.instance, '_dispatch'):
                        return self.instance._dispatch(method, params)
                    else:
                        # call instance method directly
                        try:
                            func = resolve_dotted_attribute(
                                self.instance,
                                method,
                                self.allow_dotted_names
                            )
                        except AttributeError:
                            pass

            if func is not None:
                return func(*params)
            else:
                raise Exception('method "%s" is not supported' % method)


    # Create server
    HOST, PORT = "0.0.0.0", 9090
    print('Running XML-RPC server on %s:%d' % (HOST, PORT))
    server = MySimpleXMLRPCServer((HOST, PORT),
                                  logRequests=True,
                                  requestHandler=RequestHandler,
                                  allow_none=True)
    server.register_introspection_functions()

    # add dm250k model
    ConfigParser = ConfigParser()
    ConfigParser.read(os.environ.get('HOME', '/home/pi') + '/carima/system.cfg')
    modelName = ConfigParser.get('SYSTEM', 'Model')
    print("model: ", modelName)

    if modelName == 'DM250k' or modelName == 'DM4K':
        server.register_instance(printThread_4k('DM250K'))
    elif modelName == 'KIST':
        server.register_instance(printThread_Kist('KIST'))
    elif modelName == "IMD_S":
        server.register_instance(printThread_Shofu('IMD_S'))
    else:
        server.register_instance(printThread('IMD'))

    # Run the server's main loop
    server.serve_forever()
    print('Stop XML-RPC server on %s:%d') % (HOST, PORT)

# 1.0.0.19 (Shofu_1.0.0.17) / (2022.09.28)