from core.models.develop.user import User, get_fields, get_fields_form
from core.utils.packages import application, session
from flask import Blueprint, render_template, request, flash, redirect, url_for, current_app
from core.utils.db import db
from werkzeug.utils import secure_filename
from flask_login import login_required
from flask_login import current_user
from werkzeug.security import generate_password_hash
import os

classname = "user"
Record = User

blueprintname = Blueprint("user", __name__)
auth = [1,2]
def authorization():
    if current_user.usergroup.id in auth:
        return True
    return False

@blueprintname.route(f'/admin/{classname}/new/', methods=["GET","POST"])
@login_required
def create_record():
    if authorization():
        fields = get_fields_form()
        session.updateHistory()
        backlink = url_for('.list_record')
        if request.method == "GET":
            return render_template("backend/base/user.html",fields=fields,backlink=backlink,editable=True)
        elif request.method == "POST":

            newuser = Record()
            session.saveForm(newuser,fields)
            pwd = request.form["password"]
            newuser.set_password(pwd)
            db.session.add(newuser)
            db.session.commit()

            return redirect(url_for('.view_record', record_id=newuser.id,fields=fields,backlink=backlink,editable=True))
        return redirect(url_for('frontend.index'))
    
@blueprintname.route(f'/admin/{classname}/<int:record_id>')
@login_required
def view_record(record_id):
    if authorization() or current_user.id == record_id:
        cmd = request.args.get('cmd')
        if cmd == "stop":
            session.updateHistory(-1)
        else:
            session.updateHistory()
        backlink = url_for('.list_record')
        fields = get_fields_form()
        record = Record.query.get_or_404(record_id)
        return render_template('backend/base/user.html', record=record, fields=fields,backlink=backlink,editable=False)
    return redirect(url_for('frontend.index'))

@blueprintname.route(f'/admin/{classname}/<int:record_id>/edit/', methods=['GET', 'POST'])
@login_required
def edit_record(record_id):
    if authorization() or current_user.id == record_id:
        fields = get_fields_form()
        session.updateHistory()
        backlink = url_for('.view_record', record_id=record_id,editable=False)
        record = Record.query.get_or_404(record_id)
        if request.method == 'POST':
            session.saveForm(record,fields)
            pwd = request.form["password"]
            if pwd:
                record.set_password(pwd)
            db.session.commit()
            flash('La institución ha sido actualizada exitosamente.', 'success')
            return render_template('backend/base/user.html', record=record, fields=fields, editable=True, backlink=backlink)
        return render_template('backend/base/user.html', record=record, fields=fields, editable=True, backlink=backlink)

@blueprintname.route(f'/admin/{classname}/<int:record_id>/delete/', methods=['POST'])
@login_required
def delete_record(record_id):
    if authorization():
        class_names = application.list_class_names()
        institution = Record.query.get_or_404(record_id)
        db.session.delete(institution)
        db.session.commit()
        flash('La institución ha sido eliminada exitosamente.', 'success')
        return redirect(url_for('.list_record'))  
    return redirect(url_for('frontend.index'))

@blueprintname.route(f'/admin/{classname}/all/')
@login_required
def list_record():
    if authorization():
        class_names = application.list_class_names()
        institutions = Record.query.filter(Record.usergroup_id != 1).all()
        return render_template('backend/base/list_user.html', institutions=institutions,classname=classname, class_names=class_names)
    return redirect(url_for('frontend.index'))
