from flask import Blueprint, render_template, redirect, url_for, request
from flask_login import login_required
from app import db
from .models import GrowLog
from .forms import GrowLogForm
from plugins.plant.models import Plant

bp = Blueprint('growlog', __name__, template_folder='templates')

@bp.route('/plants/<int:plant_id>/logs')
@login_required
def view_logs(plant_id):
    plant = Plant.query.get_or_404(plant_id)
    logs = GrowLog.query.filter_by(plant_id=plant.id).order_by(GrowLog.timestamp.desc()).all()
    return render_template('growlog/log_list.html', plant=plant, logs=logs)

@bp.route('/plants/<int:plant_id>/logs/add', methods=['GET', 'POST'])
@login_required
def add_log(plant_id):
    plant = Plant.query.get_or_404(plant_id)
    form = GrowLogForm()
    if form.validate_on_submit():
        log = GrowLog(
            plant_id=plant.id,
            event_type=form.event_type.data,
            note=form.note.data
        )
        db.session.add(log)
        db.session.commit()
        return redirect(url_for('growlog.view_logs', plant_id=plant.id))
    return render_template('growlog/log_form.html', form=form, plant=plant)