def register(n):
    nav = utils.nav([["/",app.getFn()],["Register"]])

    er = ""
    if n:
        if n == 1:
            erno = "Username already in use"
        elif erno == 2:
            erno = "Passwords don't match"
        er = '<div class="alert alert-danger"><strong>Error:</strong> %s</div>'%(erno)

    return """
<div id="header">Register</div>%s
<div style="width:300px;margin-left:auto;margin-right:auto;">
%s
<form method="post">
<table class="table">
<tr class="active"><td><input tabindex="1" name="username" type="text" class="form-control" placeholder="Username" /></td></tr>
<tr class="active"><td><input tabindex="2" name="password" type="password" class="form-control" placeholder="Password" /></td></tr>
<tr class="active"><td><input tabindex="3" name="password2" type="password" class="form-control" placeholder="Confirm Password" /></td></tr>
<tr class="active"><td style="text-align:center">Already have an account?  Login by clicking <a href="login">here</a></td></tr>
<tr class="active"><td style="text-align:center"><input tabindex="4" type="submit" class="btn btn-primary" value="Register" /></td></tr>
</table>
</form>
</div>%s"""%(nav,er,nav)
def index():
    # type:
    # 1 = logged out
    # 2 = registered
    # 3 = logged in
    uid = getUID()
    nav = utils.nav([[fn]])
    r = ""

    r += '<div id="header">Forum</div>'
    r += nav

    tp = request.args.get("type")
    mes = ""
    if tp == '1':
        mes = "You have logged out."
    elif tp == '2':
        mes = "Account registration successful!"
    elif tp == '3':
        mes = "You have logged in."

    if mes:
        r += '<div class="alert alert-success"><strong>Success</strong>: %s</div>'%(mes)

    r += """
<table class="table" cellspacing="0">
<tr class="active">
<th>Forum Name</th>
<th class="f_num">Threads</th>
<th class="f_num">Posts</th>
<th class="f_last">Last Post</th>
"""
    for x in c.forums.Collections.find():
        r += html.forum(x)
    r += '</table>'
    
    r += """
<table class="table">
<tr class="active">
<th>Forum Statistics</th>
</tr>
<tr class="active">
<td>
Total Posts: <strong>%d</strong><br />
Total Threads: <strong>%d</strong><br />
Total Users: <strong>%d</strong>
</td>
</tr>
</table>"""%(c.posts.Collections.find().count(),c.threads.Collections.find().count(),c.users.Collections.find().count())




    r += nav


    return page(r,uid)
def forum(n):
    # type:
    # 1 = thread deleted
    uid = getUID()
    r = ""
    
    forum = getForum(n)
    if forum:

        nav = utils.nav([
                ["/",fn],
                [forum["name"]]
                ])

        options = ""
        if uid != -1:
            options = '<div class="options"><a href="newthread-%d" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Create New Thread</a></div>'%(forum['id'])

        r += '<div id="header">%s</div>'%(forum['name'])
        r += nav

        tp = request.args.get("type")
        mes = ""
        if tp == '1':
            mes = "Thread deleted."

        if mes:
            r += '<div class="alert alert-success"><strong>Success</strong>: %s</div>'%(mes)


        r += options
        r += """<table class="table" cellspacing="0">
<tr class="active"><th class="t_title">Thread Title</th><th class="t_author">Author</th><th class="t_num">Posts</th><th>Last Post</th></tr>
"""
        thr = c.threads.Collections.find({"fid":forum['id']})
        if thr.count() == 0:
            r += '<tr class="active"><td colspan="4">No threads exist in this forum</td></tr>'
        else:
            for x in thr:
                r += html.thread(x,admin(uid))
        r += '</table>'
        r += options
        r += nav

        return page(r,uid)
def delthread(n):
    thread = getThread(n)
    forum = getForum(thread["fid"])
    nav = utils.nav([
            ["/",app.getFn()],
            ["/forum-%d"%(forum['id']),forum["name"]],
            ["thread-%d"%(thread['id']),thread["title"]],
            ["Delete Thread"]
            ])

    r = """
<div id="header">Are you sure you wish to delete this thread?</div>%s
<form method="post">
<input type="hidden" name="tid" value="%d" />
<div style="text-align:center">
<input type="submit" value="Yes, delete this thread" class="btn btn-danger" name="del" />
<br /><br /><a href="thread-%d">No, take me back to the thread</a>
</div>
</form>%s"""%(nav,n,n,nav)
    return r
def login(n):
    nav = utils.nav([["/",app.getFn()],["Login"]])

    er = ""
    if n:
        if n == 1:
            erno = "Username/password combination does not exist"
        er = '<div class="alert alert-danger"><strong>Error:</strong> %s</div>'%(erno)

    return """
<div id="header">Login</div>%s
<div style="width:300px;margin-left:auto;margin-right:auto;">
%s
<form method="post">
<table class="table">
<tr class="active"><td><input tabindex="1" name="username" type="text" class="form-control" placeholder="Username" /></td></tr>
<tr class="active"><td><input tabindex="2" name="password" type="password" class="form-control" placeholder="Password" /></td></tr>
<tr class="active"><td style="text-align:center">Don't have an account?  Register an account by clicking <a href="register">here</a></td></tr>
<tr class="active"><td style="text-align:center"><input tabindex="3" type="submit" class="btn btn-primary" value="Login" /></td></tr>
</table>
</form>
</div>%s"""%(nav,er,nav)
def newthread(n):
    forum = getForum(n)
    nav = utils.nav([
            ["/",app.getFn()],
            ["/forum-%d"%(forum['id']),forum["name"]],
            ["Create New Thread"]
            ])

    r = """
<div id="header">Create New Thread</div>%s
<form method="post">
<input type="hidden" name="fid" value="%d" />
<table class="table">
<tr class="active"><td><div class="col-xs-3"><input name="title" type="text" class="form-control" placeholder="Enter your title here..."  /></div></td></tr>
<tr class="active"><td><div class="col-xs-8"><input name="desc" type="text" class="form-control" placeholder="Enter a description here... (Optional)"  /></div></td></tr>
<tr class="active"><td><textarea name="content" class="form-control" rows="12" placeholder="Enter your post here..."></textarea></td></tr>
<tr class="active"><td style="text-align:center;">
  <input type="submit" class="btn btn-primary" value="Create Thread" name="reply" />
  <input type="submit" class="btn btn-primary" value="Cancel" name="cancel" />
</td></tr>
</table>
</form>%s"""%(nav,n,nav)
    return r
def reply(n):
    thread = getThread(n)
    forum = getForum(thread["fid"])
    nav = utils.nav([
            ["/",app.getFn()],
            ["/forum-%d"%(forum['id']),forum["name"]],
            ["thread-%d"%(thread['id']),thread["title"]],
            ["Reply"]
            ])

    r = """
<div id="header">Reply</div>%s
<form method="post">
<input type="hidden" name="tid" value="%d" />
<table class="table">
<tr class="active"><td><textarea name="content" class="form-control" rows="12" placeholder="Enter your post here..."></textarea></td></tr>
<tr class="active"><td style="text-align:center;">
  <input type="submit" class="btn btn-primary" value="Reply" name="reply" />
  <input type="submit" class="btn btn-primary" value="Cancel" name="cancel" />
</td></tr>
</table>
</form>%s"""%(nav,n,nav)
    return r
def edittitle(n):
    thread = getThread(n)
    forum = getForum(thread["fid"])
    nav = utils.nav([
            ["/",app.getFn()],
            ["/forum-%d"%(forum['id']),forum["name"]],
            ["thread-%d"%(thread['id']),thread["title"]],
            ["Edit Thread Title"]
            ])

    r = """
<div id="header">Edit Thread Title</div>%s
<form method="post">
<input type="hidden" name="tid" value="%d" />
<table class="table">
<tr class="active"><td><div class="col-xs-3"><input name="title" type="text" class="form-control" placeholder="Enter your title here..." value="%s" /></div></td></tr>
<tr class="active"><td><div class="col-xs-8"><input name="desc" type="text" class="form-control" placeholder="Enter a description here... (Optional)" value="%s" /></div></td></tr>
<tr class="active"><td>
  <input type="submit" class="btn btn-primary" value="Edit Title" name="reply" />
  <a class="btn btn-primary" href="thread-%d">Cancel</a>
</td></tr>
</table>
</form>%s"""%(nav,n,cgi.escape(thread["title"]),cgi.escape(thread["desc"]),n,nav)
    return r
def thread(n):
    uid = getUID()


    r = ""

    thread = getThread(n)
    
    if thread:
        # if thread is hidden and cannot view
        if thread['hid'] and not admin(uid):
            return page(html.permissionDenied(),uid)

        posts = c.posts.Collections.find({"tid":thread['id']}).sort("id",1)
        # pages
        pg = 1
        p = request.args.get("page")
        if p:
            pg = int(p)

        pghtml = html.pages(pg,int((posts.count()-1)/config.postsPerPage())+1,"thread-%d?page="%(thread['id']))

        forum = getForum(thread["fid"])
        nav = utils.nav([
                ["/",fn],
                ["/forum-%d"%(forum['id']),forum["name"]],
                [thread["title"]]
                ])


        atools = ""



        # admin tools
        if admin(uid):
            atools += """
<table class="table">
<tr class="warning">
<td style="width:150px;text-align:center;font-weight:bold;">Administrative<br />Tools</td>
<td style="vertical-align:middle;">
<a href="edittitle-%d" class="btn btn-warning"><span class="glyphicon glyphicon-pencil"></span> Edit Thread Title</a>"""%(thread['id'])

            # lock/unlock
            if "lock" in thread.keys() and thread['lock']:
                atools += ' <a href="unlockthread-%d" class="btn btn-success"><span class="glyphicon glyphicon-lock"></span> Unlock Thread</a>'%(thread['id'])
            else:
                atools += ' <a href="lockthread-%d" class="btn btn-danger"><span class="glyphicon glyphicon-lock"></span> Lock Thread</a>'%(thread['id'])

            # hide/unhide
            if "hid" in thread.keys() and thread['hid']:
                atools += ' <a href="unhidethread-%d" class="btn btn-success"><span class="glyphicon glyphicon-eye-open"></span> Unhide Thread</a>'%(thread['id'])
            else:
                atools += ' <a href="hidethread-%d" class="btn btn-danger"><span class="glyphicon glyphicon-eye-close"></span> Hide Thread</a>'%(thread['id'])
            atools += """
<a href="delthread-%d" class="btn btn-danger deleteThread"><span class="glyphicon glyphicon-remove"></span> Delete Thread</a>
</td>
</tr>
</table>"""%(thread['id'])

        options = ""
        if uid != -1 and (not thread['lock'] or admin(uid)):
            options = '<div class="options"><a href="reply-%d" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Reply</a></div>'%(thread['id'])


        r += '<div id="header">%(title)s</div><div class="description">%(desc)s</div>'%(thread)

        r += '<div class="thread_info">'

        if thread['lock']:
            r += '<span class="alert alert-danger"><span class="glyphicon glyphicon-lock"></span> Locked</span>'
        if thread['hid']:
            r += '<span class="alert alert-danger"><span class="glyphicon glyphicon-eye-close"></span> Hidden</span>'
        
        r += '</div>'

        mes = request.args.get("type")
        if mes == '1':
            mes = "Thread title edited"
        elif mes == '2':
            mes = "Thread hidden"
        elif mes == '3':
            mes = "Thread unhidden"
        elif mes == '4':
            mes = "Thread locked"
        elif mes == '5':
            mes = "Thread unlocked"
        elif mes == '51':
            mes = "Post deleted"
        elif mes == '52':
            mes = "Post edited"



        r += nav
        if mes:
            r += '<div class="alert alert-success"><strong>Success:</strong> %s</div>'%(mes)
        r += atools
        r += pghtml
        r += options
        r += '<div id="posts">'


        ppp = config.postsPerPage()
        for x in range((pg-1)*ppp,min(pg*ppp,posts.count())):
            r += html.post(uid,posts[x])

        r += '</div>'
        r += options
        r += pghtml
        r += nav

        return page(r,uid)
    else:
        return page(html.threadDoesNotExist(),uid)