from flask import Blueprint, render_template, request, redirect, url_for, flash, current_app

from src.models import Setting
import config

settings_bp = Blueprint("settings", __name__)


@settings_bp.route("/settings", methods=["GET"])
def index():
    feed_url = Setting.get("feed_url", default=config.FEED_URL)
    fetch_interval = Setting.get("fetch_interval_hours", default=config.FETCH_INTERVAL_HOURS)
    auto_publish = Setting.get("auto_publish", default=None)
    max_landscape = Setting.get("image_max_landscape", default=list(config.IMAGE_MAX_LANDSCAPE))
    max_portrait = Setting.get("image_max_portrait", default=list(config.IMAGE_MAX_PORTRAIT))

    return render_template(
        "settings.html",
        feed_url=feed_url,
        fetch_interval=fetch_interval,
        auto_publish=auto_publish,
        max_landscape=max_landscape,
        max_portrait=max_portrait,
    )


@settings_bp.route("/settings", methods=["POST"])
def update():
    feed_url = request.form.get("feed_url", config.FEED_URL)
    fetch_interval = int(request.form.get("fetch_interval", config.FETCH_INTERVAL_HOURS))

    Setting.set("feed_url", feed_url)
    config.FEED_URL = feed_url

    scheduler_mgr = current_app.config.get("SCHEDULER_MANAGER")
    if scheduler_mgr:
        scheduler_mgr.update_fetch_interval(fetch_interval)

    auto_enabled = request.form.get("auto_publish_enabled") == "on"
    if auto_enabled:
        day = request.form.get("auto_publish_day", "sun")
        hour = int(request.form.get("auto_publish_hour", 6))
        minute = int(request.form.get("auto_publish_minute", 0))
        method = request.form.get("auto_publish_cover", "text")
        if scheduler_mgr:
            scheduler_mgr.enable_auto_publish(day, hour, minute, method)
    else:
        if scheduler_mgr:
            scheduler_mgr.disable_auto_publish()

    lw = int(request.form.get("landscape_w", 800))
    lh = int(request.form.get("landscape_h", 480))
    pw = int(request.form.get("portrait_w", 480))
    ph = int(request.form.get("portrait_h", 800))
    Setting.set("image_max_landscape", [lw, lh])
    Setting.set("image_max_portrait", [pw, ph])
    config.IMAGE_MAX_LANDSCAPE = (lw, lh)
    config.IMAGE_MAX_PORTRAIT = (pw, ph)

    flash("Settings saved.")
    return redirect(url_for("settings.index"))
