import os
from quixote import get_response
from quixote.ptl import ptl_html
from quixote.directory import Directory, Resolving
from quixote.util import StaticDirectory
from quixote.demo.integers import IntegerUI
from quixote.http_response import Stream


class ExtraDirectory(Resolving, Directory):

    _q_exports = ["", "form", "src", "chunked"]

    @ptl_html
    def _q_index(self):
        F"""
        <html>
        <head><title>Quixote Demo Extras</title></head>
        <body>
        <h1>Extras</h1>
        <p>
        Here are some more features of this demo:
          <ul>
            <li><a href="12/">12/</a>:
                A Python object published through <code>_q_lookup()</code>.
            <li><a href="12/factorial">12/factorial</a>:
                A method on a published Python object.
            <li><a href="form">form</a>:
                A Quixote form in action.
            <li><a href="src/">src/</a>:
                A static directory published through Quixote.
            <li><a href="chunked">chunked</a>:
                A page on indeterminate length using chunked transfer
                encoding.
          </ul>
        """

    def _q_resolve(self, component):
        # _q_resolve() is a hook that can be used to import only
        # when it's actually accessed.  This can be used to make
        # start-up of your application faster, because it doesn't have
        # to import every single module when it starts running.
        if component == 'form':
            from quixote.demo.forms import form_demo

            return form_demo

    def _q_lookup(self, component):
        return IntegerUI(component)

    def upload(self):
        return 'upload demo unfinished'

    def chunked(self):
        def gen_content():
            yield 'The server does not know how long this will be.\n'
            for i in range(30):
                yield 'line %d\n' % i

        get_response().set_content_type('text/plain')
        return Stream(gen_content())

    import quixote

    src = StaticDirectory(
        os.path.dirname(quixote.__file__), list_directory=True
    )
