# coding=utf-8
"""" Simple DEBUG SERVICE plugin

http://localhost:8080/cgi-bin/qgis_mapserv.cgi?SERVICE=DEBUG

.. note:: This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

"""

__author__ = 'wanzhongping'
__date__ = '2021-04-20'
__copyright__ = 'chinadci'


import os
from dmap_server import *


class DebugFilter(DmpServerFilter):

    def request_ready(self):
        handler = self.server_interface().request_handler()
        params = handler.parameters()
        if len(params) == 0:
            return
        if 'DEBUG' in params:
            handler.set_parameter('SERVICE', 'DEBUG')
        print("request_ready")

    def response_complete(self):
        handler = self.server_interface().request_handler()
        params = handler.parameters()
        if len(params) == 0:
            return
        if params['service'] != 'DEBUG':
            return

        headers_dict = handler.request_headers()
        handler.clear()
        handler.set_response_header('Status', '200 Ok')
        handler.append_body(b'<h1>Params</h1>')
        for param in params:
            handler.append_body(('<p><b>%s</b> "%s"</p>' % (param.key(), param.data())).encode('utf8'))
            # handler.append_body('<p><b>%s</b> "%s"</p>' % (param.key(), param.data()))

        handler.append_body('<h1>Headers</h1>'.encode('utf8'))
        for header in headers_dict:
            handler.append_body(('<p><b>%s</b> "%s"</p>' % (header.key(), header.data())).encode('utf8'))
        print("response_complete")

 
class Debug:

    def __init__(self, serverIface):
        # Save reference to the DMap server interface
        # Higher priority
        self.debugFilter = DebugFilter(serverIface)
        serverIface.register_filter(self.debugFilter, 10)