#!/usr/bin/env python3
import os
import sqlite3
from http.server import ThreadingHTTPServer
from urllib.parse import urlparse

import mysql_preview_server as base


class ProjectCodeViewerHandler(base.Handler):
    def do_GET(self):
        parsed = urlparse(self.path)
        if parsed.path == '/':
            return self._html(base.PROJECT_CODES_HTML)
        return super().do_GET()


if __name__ == '__main__':
    os.makedirs(base.BASE_DIR, exist_ok=True)
    try:
        with sqlite3.connect(base.DB_PATH, timeout=30) as conn:
            base.init_db(conn)
    except sqlite3.OperationalError as error:
        if 'locked' in str(error).lower():
            print(f'Skip startup DB init because database is locked: {error}')
        else:
            raise
    port = int(os.environ.get('PORT', '8092'))
    host = '0.0.0.0'
    print(f'Server running: http://{base.local_ip()}:{port}')
    print(f'Local access:   http://127.0.0.1:{port}')
    print('Tip: root path serves the project code viewer page.')
    ThreadingHTTPServer((host, port), ProjectCodeViewerHandler).serve_forever()
