from flask import (
    abort,
    flash, 
    redirect, 
    render_template, 
    send_from_directory,
    url_for
)
from flask_breadcrumbs import register_breadcrumb
from flask_login import current_user, login_required
import os
from app import db
from app.models import Avatar, Corpus, ProfilePrivacySettings, User
from . import bp
from .forms import (
  ChangePasswordForm,
  EditNotificationSettingsForm,  
  EditPrivacySettingsForm,
  EditProfileSettingsForm,
  EditPublicProfileInformationForm
)
from .utils import (
    user_endpoint_arguments_constructor as user_eac,
    user_dynamic_list_constructor as user_dlc
)


@bp.route('')
@register_breadcrumb(bp, '.', '<i class="material-icons left">group</i>Social Area')
@login_required
def users():
    return redirect(url_for('main.social_area', _anchor='users'))


@bp.route('/<hashid:user_id>')
@register_breadcrumb(bp, '.entity', '', dynamic_list_constructor=user_dlc)
@login_required
def user(user_id):
    user = User.query.get_or_404(user_id)
    last_seen = user.last_seen.strftime('%Y-%m-%d %H:%M')
    member_since = user.member_since.strftime('%Y-%m-%d')
    followed_corpora = [
        c.to_json_serializeable() for c in user.followed_corpora
    ]
    own_public_corpora = [
        c.to_json_serializeable() for c
        in Corpus.query.filter_by(is_public = True, user = user).all()
    ]
    if not user.is_public and user != current_user:
        abort(403)
    return render_template(
        'users/profile.html.j2',
        followed_corpora=followed_corpora,
        last_seen=last_seen,
        member_since=member_since,
        own_public_corpora=own_public_corpora,
        user=user.to_json_serializeable(),
        user_id=user_id,
        title=user.username
    )


@bp.route('/<hashid:user_id>/avatar')
@login_required
def profile_avatar(user_id):
    user = User.query.get_or_404(user_id)
    if user.avatar is None:
        return redirect(url_for('static', filename='images/user_avatar.png'))
    if not user.is_public and not (user == current_user or current_user.is_administrator()):
        abort(403)
    return send_from_directory(
        os.path.dirname(user.avatar.path),
        os.path.basename(user.avatar.path),
        as_attachment=True,
        attachment_filename=user.avatar.filename,
        mimetype=user.avatar.mimetype
    )


@bp.route('/<hashid:user_id>/edit', methods=['GET', 'POST'])
@register_breadcrumb(bp, '.entity.edit', '<i class="material-icons left">settings</i>Edit', endpoint_arguments_constructor=user_eac)
@login_required
def edit_profile(user_id):
    user = User.query.get_or_404(user_id)
    if not (user == current_user or current_user.is_administrator()):
        abort(403)
    # region forms
    edit_profile_settings_form = EditProfileSettingsForm(
        current_user,
        data=current_user.to_json_serializeable(),
        prefix='edit-profile-settings-form'
    )
    edit_privacy_settings_form = EditPrivacySettingsForm(
        data=current_user.to_json_serializeable(),
        prefix='edit-privacy-settings-form'
    )
    edit_public_profile_information_form = EditPublicProfileInformationForm(
        data=current_user.to_json_serializeable(),
        prefix='edit-public-profile-information-form'
    )
    change_password_form = ChangePasswordForm(
        current_user,
        prefix='change-password-form'
    )
    edit_notification_settings_form = EditNotificationSettingsForm(
        data=current_user.to_json_serializeable(),
        prefix='edit-notification-settings-form'
    )
    # endregion forms
    # region handle edit profile settings form
    if edit_profile_settings_form.validate_on_submit():
        current_user.email = edit_profile_settings_form.email.data
        current_user.username = edit_profile_settings_form.username.data
        db.session.commit()
        flash('Profile settings updated')
        return redirect(url_for('.user', user_id=user.id))
    # endregion handle edit profile settings form
    # region handle edit privacy settings form
    if edit_privacy_settings_form.submit.data and edit_privacy_settings_form.validate():
        current_user.is_public = edit_privacy_settings_form.is_public.data
        if edit_privacy_settings_form.show_email.data:
            current_user.add_profile_privacy_setting(ProfilePrivacySettings.SHOW_EMAIL)
        else:
            current_user.remove_profile_privacy_setting(ProfilePrivacySettings.SHOW_EMAIL)
        if edit_privacy_settings_form.show_last_seen.data:
            current_user.add_profile_privacy_setting(ProfilePrivacySettings.SHOW_LAST_SEEN)
        else:
            current_user.remove_profile_privacy_setting(ProfilePrivacySettings.SHOW_LAST_SEEN)
        if edit_privacy_settings_form.show_member_since.data:
            current_user.add_profile_privacy_setting(ProfilePrivacySettings.SHOW_MEMBER_SINCE)
        else:
            current_user.remove_profile_privacy_setting(ProfilePrivacySettings.SHOW_MEMBER_SINCE)
        db.session.commit()
        flash('Your changes have been saved')
        return redirect(url_for('.user', user_id=user.id))
    # endregion handle edit privacy settings form
    # region handle edit public profile information form
    if edit_public_profile_information_form.submit.data and edit_public_profile_information_form.validate():
        if edit_public_profile_information_form.avatar.data:
            try:
                Avatar.create(edit_public_profile_information_form.avatar.data, user=current_user)
            except (AttributeError, OSError):
                abort(500)
        current_user.about_me = edit_public_profile_information_form.about_me.data
        current_user.location = edit_public_profile_information_form.location.data
        current_user.organization = edit_public_profile_information_form.organization.data
        current_user.website = edit_public_profile_information_form.website.data
        current_user.full_name = edit_public_profile_information_form.full_name.data
        db.session.commit()
        flash('Profile settings updated')
        return redirect(url_for('.user', user_id=user.id))
    # endregion handle edit public profile information form
    # region handle change_password_form POST
    if change_password_form.submit.data and change_password_form.validate():
        current_user.password = change_password_form.new_password.data
        db.session.commit()
        flash('Your changes have been saved')
        return redirect(url_for('.edit_profile', user_id=user.id))
    # endregion handle change_password_form POST
    # region handle edit_notification_settings_form POST
    if edit_notification_settings_form.submit and edit_notification_settings_form.validate():
        current_user.setting_job_status_mail_notification_level = edit_notification_settings_form.job_status_mail_notification_level.data
        db.session.commit()
        flash('Your changes have been saved')
        return redirect(url_for('.edit_profile', user_id=user.id))
    # endregion handle edit_notification_settings_form POST
    return render_template(
        'users/edit_profile.html.j2',
        edit_profile_settings_form=edit_profile_settings_form,
        edit_privacy_settings_form=edit_privacy_settings_form,
        edit_public_profile_information_form=edit_public_profile_information_form,
        change_password_form=change_password_form,
        edit_notification_settings_form=edit_notification_settings_form,
        user=user,
        title='Edit Profile'
    )
