"""board.py - put the homework list on the school wifi.

This is the SAME homework.db from the homework.py app. We are not making a
new program. We are putting a second face on the one you already have.

    pip3 install flask
    python3 board.py

Then open http://localhost:5000 on this computer.
Students on the same wifi open http://<your address>:5000 on their phones.

WARNING, and read it properly: this is Flask's built-in server. It is made
for building and testing, not for the open internet. On the school wifi for
one class is fine. Do not put it on the real internet.
"""
import socket
import sqlite3
from pathlib import Path

from flask import Flask, redirect, render_template, request, url_for

DB_PATH = Path(__file__).with_name("homework.db")

app = Flask(__name__)


def open_db():
    conn = sqlite3.connect(DB_PATH)
    conn.execute("""CREATE TABLE IF NOT EXISTS jobs (
        id      INTEGER PRIMARY KEY,
        student TEXT NOT NULL,
        title   TEXT NOT NULL,
        due     TEXT,
        done    INTEGER NOT NULL DEFAULT 0
    )""")
    conn.commit()
    return conn


@app.route("/", methods=["GET", "POST"])
def board():
    conn = open_db()
    try:
        if request.method == "POST":
            student = request.form.get("student", "").strip()
            title = request.form.get("title", "").strip()
            if student and title:
                conn.execute(
                    "INSERT INTO jobs (student, title, due) VALUES (?, ?, ?)",
                    (student, title, request.form.get("due", "").strip() or None),
                )
                conn.commit()
            # Send the browser away to a fresh GET. Without this, pressing
            # refresh sends the same job again, and again, and again.
            return redirect(url_for("board"))

        jobs = conn.execute(
            "SELECT id, student, title, due, done FROM jobs ORDER BY done, id"
        ).fetchall()
        return render_template("board.html", jobs=jobs)
    finally:
        conn.close()


@app.route("/done/<int:job_id>", methods=["POST"])
def done(job_id):
    conn = open_db()
    try:
        conn.execute("UPDATE jobs SET done = 1 WHERE id = ?", (job_id,))
        conn.commit()
    finally:
        conn.close()
    return redirect(url_for("board"))


def my_address():
    """Find the address other phones on this wifi should type."""
    probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        probe.connect(("8.8.8.8", 80))      # nothing is sent; this just picks a route
        return probe.getsockname()[0]
    except Exception:
        return "127.0.0.1"
    finally:
        probe.close()


if __name__ == "__main__":
    print("On this computer:  http://localhost:5000")
    print("On the wifi:       http://%s:5000" % my_address())
    # 0.0.0.0 means "listen to the whole room", not just this computer.
    app.run(host="0.0.0.0", port=5000, debug=False)
