from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from app import db
from app.models.dictionary import DictionaryEntry
from app.forms.teacher.dictionary import DictionaryEntryForm

# Use the main teacher blueprint instead of creating a separate one
from app.routes.teacher import bp

@bp.route('/')
@login_required
def manage_dictionary():
    entries = DictionaryEntry.query.order_by(DictionaryEntry.created_at.desc()).all()
    return render_template('teacher/dictionary/manage.html', dictionary_entries=entries)

@bp.route('/add', methods=['GET', 'POST'])
@login_required
def add_dictionary_word():
    form = DictionaryEntryForm()
    if form.validate_on_submit():
        word = form.word.data.strip()
        existing_entry = DictionaryEntry.query.filter_by(word=word).first()
        if existing_entry:
            flash('This word already exists in the dictionary!', 'error')
            return render_template('teacher/dictionary/add.html', form=form)
        entry = DictionaryEntry(
            word=word,
            definition=form.definition.data.strip(),
            synonyms=form.synonyms.data.strip() if form.synonyms.data else None,
            antonyms=form.antonyms.data.strip() if form.antonyms.data else None,
            example_sentence=form.example_sentence.data.strip() if form.example_sentence.data else None,
            suggestion=form.suggestion.data.strip() if form.suggestion.data else None,
            added_by=current_user
        )
        db.session.add(entry)
        db.session.commit()
        flash('Word of the day added!', 'success')
        return redirect(url_for('teacher.manage_dictionary'))
    return render_template('teacher/dictionary/add.html', form=form)

@bp.route('/edit/<int:word_id>', methods=['GET', 'POST'])
@login_required
def edit_dictionary_word(word_id):
    entry = DictionaryEntry.query.get_or_404(word_id)
    form = DictionaryEntryForm(obj=entry)
    if form.validate_on_submit():
        entry.word = form.word.data.strip()
        entry.definition = form.definition.data.strip()
        entry.synonyms = form.synonyms.data.strip() if form.synonyms.data else None
        entry.antonyms = form.antonyms.data.strip() if form.antonyms.data else None
        entry.example_sentence = form.example_sentence.data.strip() if form.example_sentence.data else None
        entry.suggestion = form.suggestion.data.strip() if form.suggestion.data else None
        db.session.commit()
        flash('Word updated!', 'success')
        return redirect(url_for('teacher.manage_dictionary'))
    return render_template('teacher/dictionary/edit.html', form=form)
