from flask import Blueprint, redirect, render_template, request, flash, session

from database import base
from database.base import User
from forms import UserForm, LoginForm, MyPageUserForm
from flask_login import login_required, login_user, logout_user, current_user
import requests

auth_blueprint = Blueprint('auth', __name__)

kakao_oauth = {}

@auth_blueprint.route('/my_page', methods=['GET', 'POST'])
@login_required
def _user():
    form = MyPageUserForm()

    q = base.db_session.query(User).filter(User.email == current_user.email)
    user = q.first()

    if request.method == 'POST':
        if form.validate_on_submit():
            user.email = request.form['email']
            user.name = request.form['name']
            user.set_password(request.form['password'])
            user.affiliation = request.form['affiliation']
            base.db_session.commit()
            flash('귀하의 회원정보가 수정 되었습니다.')
            return redirect('/auth/my_page')

    return render_template("my_page.html", user=user, form=form, kakao_oauth=kakao_oauth)


def login_process(email, password):
    q = base.db_session.query(User).filter(User.email == email)
    user = q.first()

    if user:
        if user.authenticate(password):
            login_result = login_user(user)
            if login_result:
                print("사용자(사용자 이메일:{0})의 로그인 성공!".format(current_user.email))
            return '/'
        else:
            flash('비밀번호를 다시 확인하여 입력해주세요.')
            return '/auth/login'
    else:
        flash('이메일 및 비밀번호를 다시 확인하여 입력해주세요.')
        return '/auth/login'


@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect('/')

    form = LoginForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            redirect_url = login_process(form.data['email'], form.data['password'])
            return redirect(redirect_url)

    return render_template('login.html', form=form, current_user=current_user)


@auth_blueprint.route('kakao_oauth_redirect')
def kakao_oauth_redirect():
    code = str(request.args.get('code'))
    url = "https://kauth.kakao.com/oauth/token"
    data = "grant_type=authorization_code" \
            "&client_id=0eb67d9cd0372c01d3915bbd934b4f6d" \
            "&redirect_uri=http://localhost:8080/auth/kakao_oauth_redirect" \
            "&code={0}".format(code)
    headers = {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
        "Cache-Control": "no-cache"
    }
    response = requests.post(
        url=url,
        data=data,
        headers=headers
    )

    #print("kakao_oauth_redirect", response.json())

    kakao_oauth["access_token"] = response.json()["access_token"]
    kakao_oauth["expires_in"] = response.json()["expires_in"]
    kakao_oauth["refresh_token"] = response.json()["refresh_token"]
    kakao_oauth["refresh_token_expires_in"] = response.json()["refresh_token_expires_in"]
    kakao_oauth["scope"] = response.json()["scope"]
    kakao_oauth["token_type"] = response.json()["token_type"]

    if "kaccount_email" not in kakao_oauth or kakao_oauth['kaccount_email'] is None:
        kakao_me_and_signup()

    redirect_url = login_process(kakao_oauth["kaccount_email"], "1234")
    return redirect(redirect_url)


def kakao_me_and_signup():
    url = "https://kapi.kakao.com/v1/user/me"
    headers = {
        "Authorization": "Bearer {0}".format(kakao_oauth["access_token"]),
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }

    response = requests.post(
        url=url,
        headers=headers
    )

    #print("kakao_me_and_signup", response.json())

    kakao_oauth["kaccount_email"] = response.json()["kaccount_email"]
    kakao_oauth["id"] = response.json()["id"]
    kakao_oauth["kakao_profile_image"] = response.json()["properties"]["profile_image"]
    kakao_oauth["nickname"] = response.json()["properties"]["nickname"]
    kakao_oauth["kakao_thumbnail_image"] = response.json()["properties"]["thumbnail_image"]

    c = base.db_session.query(User).filter(User.email == kakao_oauth["kaccount_email"]).count()
    if c == 0:
        user = User(name=kakao_oauth["nickname"], email=kakao_oauth["kaccount_email"], affiliation=None)
        user.set_password("1234")
        base.db_session.add(user)
        base.db_session.commit()


def kakao_logout():
    url = "https://kapi.kakao.com/v1/user/logout"
    headers = {
        "Authorization": "Bearer {0}".format(kakao_oauth["access_token"])
    }
    response = requests.post(
        url=url,
        headers=headers
    )

    if response.status_code == 200:
        kakao_oauth["kaccount_email"] = None
        kakao_oauth["id"] = None
        kakao_oauth["kakao_profile_image"] = None
        kakao_oauth["nickname"] = None
        kakao_oauth["kakao_thumbnail_image"] = None


@auth_blueprint.route("/logout")
@login_required
def logout():
    logout_user()
    if kakao_oauth and "kaccount_email" in kakao_oauth:
        kakao_logout()

    return redirect('/')


@auth_blueprint.route('/signup', methods=['GET', 'POST'])
def signup():
    form = UserForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            new_user = User()
            new_user.email = request.form['email']
            new_user.name = request.form['name']
            new_user.set_password(request.form['password'])
            new_user.affiliation = request.form['affiliation']

            base.db_session.add(new_user)
            base.db_session.commit()
            flash('귀하는 회원가입이 성공적으로 완료되었습니다. 가입하신 정보로 로그인을 다시 하시기 바랍니다.')
            return redirect('/auth/login')

    return render_template("signup.html", form=form)
[(9, 'flask.Blueprint', 'Blueprint', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (16, 'forms.MyPageUserForm', 'MyPageUserForm', False, 'from forms import UserForm, LoginForm, MyPageUserForm\n'), (31, 'flask.render_template', 'render_template', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (57, 'forms.LoginForm', 'LoginForm', False, 'from forms import UserForm, LoginForm, MyPageUserForm\n'), (64, 'flask.render_template', 'render_template', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (79, 'requests.post', 'requests.post', False, 'import requests\n'), (98, 'flask.redirect', 'redirect', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (108, 'requests.post', 'requests.post', False, 'import requests\n'), (134, 'requests.post', 'requests.post', False, 'import requests\n'), (150, 'flask_login.logout_user', 'logout_user', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), (154, 'flask.redirect', 'redirect', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (159, 'forms.UserForm', 'UserForm', False, 'from forms import UserForm, LoginForm, MyPageUserForm\n'), (174, 'flask.render_template', 'render_template', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (48, 'flask.flash', 'flash', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (55, 'flask.redirect', 'redirect', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (69, 'flask.request.args.get', 'request.args.get', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (123, 'database.base.User', 'User', False, 'from database.base import User\n'), (125, 'database.base.db_session.add', 'base.db_session.add', False, 'from database import base\n'), (126, 'database.base.db_session.commit', 'base.db_session.commit', False, 'from database import base\n'), (18, 'database.base.db_session.query', 'base.db_session.query', False, 'from database import base\n'), (27, 'database.base.db_session.commit', 'base.db_session.commit', False, 'from database import base\n'), (28, 'flask.flash', 'flash', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (29, 'flask.redirect', 'redirect', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (35, 'database.base.db_session.query', 'base.db_session.query', False, 'from database import base\n'), (40, 'flask_login.login_user', 'login_user', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), (45, 'flask.flash', 'flash', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (62, 'flask.redirect', 'redirect', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (163, 'database.base.User', 'User', False, 'from database.base import User\n'), (169, 'database.base.db_session.add', 'base.db_session.add', False, 'from database import base\n'), (170, 'database.base.db_session.commit', 'base.db_session.commit', False, 'from database import base\n'), (171, 'flask.flash', 'flash', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (172, 'flask.redirect', 'redirect', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), (121, 'database.base.db_session.query', 'base.db_session.query', False, 'from database import base\n')]