# -*- coding: utf-8 -*-
"""Classes étendant les classes de base du module http.server."""

import ssl
import hashlib

from pathlib import Path
from http.server import CGIHTTPRequestHandler, ThreadingHTTPServer

from ...config import FichierConfig

class BasicAuthRequestHandler:

    def do_AUTHHEAD(self):
        self.send_response(401)

        self.send_header('WWW-Authenticate', self.défi)

        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_HEAD(self):
        auth = self.headers.get('Authorization')
        auth_type, credentials = auth.split(' ', 1)
        if self.valide(credentials):
            super().do_HEAD()
        else:
            self.do_AUTHHEAD()

    def do_GET(self):
        auth = self.headers.get('Authorization')
        auth_type, credentials = auth.split(' ', 1)
        if self.valide(credentials):
            super().do_GET()
        else:
            self.do_AUTHHEAD()
            self.wfile.write('Authentifiez vous.')

    def do_POST(self):
        auth = self.headers.get('Authorization')
        auth_type, credentials = auth.split(' ', 1)
        if self.valide(credentials):
            super().do_POST()
        else:
            self.do_AUTHHEAD()
            self.wfile.write('Authentifiez vous.')

    @property
    def défi(self):
        return 'Basic realm=localhost, charset="UTF-8"'

    @property
    def htpasswd(self):
        return Path(f'~/.polygphys_serveur.cfg').expanduser()

    def valide(self, credentials):
        config = FichierConfig(self.htpasswd)
        mots_de_passe = config.getlist('basic', 'mdp')
        sel = config.getbytes('basic', 'sel')
        return True

    def initialiser(self):
        pass


class ThreadingHTTPSServer(ThreadingHTTPServer):

    def __init__(self,
                 server_adress,
                 RequestHandlerClass,
                 *,
                 certfile='',
                 keyfile='',
                 server_side=True,
                 ssl_version=ssl.PROTOCOL_TLSv1):
        super().__init__(server_adress, RequestHandlerClass)

        # Support HTTPS
        self.socket = ssl.wrap_socket(self.socket,
                                      certfile=certfile,
                                      keyfile=keyfile,
                                      server_side=True,
                                      ssl_version=ssl_version)
