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, 17, 9, 44), 'flask.Blueprint', 'Blueprint', ({(9, 27, 9, 33): '"""auth"""', (9, 35, 9, 43): '__name__'}, {}), "('auth', __name__)", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((16, 11, 16, 27), 'forms.MyPageUserForm', 'MyPageUserForm', ({}, {}), '()', False, 'from forms import UserForm, LoginForm, MyPageUserForm\n'), ((31, 11, 31, 89), 'flask.render_template', 'render_template', (), '', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((57, 11, 57, 22), 'forms.LoginForm', 'LoginForm', ({}, {}), '()', False, 'from forms import UserForm, LoginForm, MyPageUserForm\n'), ((64, 11, 64, 78), 'flask.render_template', 'render_template', (), '', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((79, 15, 83, 5), 'requests.post', 'requests.post', (), '', False, 'import requests\n'), ((98, 11, 98, 33), 'flask.redirect', 'redirect', ({(98, 20, 98, 32): 'redirect_url'}, {}), '(redirect_url)', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((108, 15, 111, 5), 'requests.post', 'requests.post', (), '', False, 'import requests\n'), ((134, 15, 137, 5), 'requests.post', 'requests.post', (), '', False, 'import requests\n'), ((150, 4, 150, 17), 'flask_login.logout_user', 'logout_user', ({}, {}), '()', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((154, 11, 154, 24), 'flask.redirect', 'redirect', ({(154, 20, 154, 23): '"""/"""'}, {}), "('/')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((159, 11, 159, 21), 'forms.UserForm', 'UserForm', ({}, {}), '()', False, 'from forms import UserForm, LoginForm, MyPageUserForm\n'), ((174, 11, 174, 52), 'flask.render_template', 'render_template', (), '', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((48, 8, 48, 86), 'flask.flash', 'flash', ({(48, 14, 48, 85): '"""이메일 및 비밀번호를 다시 확인하여 입력해주세요."""'}, {}), "('이메일 및 비밀번호를 다시 확인하여 입력해주세요.')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((55, 15, 55, 28), 'flask.redirect', 'redirect', ({(55, 24, 55, 27): '"""/"""'}, {}), "('/')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((69, 15, 69, 39), 'flask.request.args.get', 'request.args.get', ({(69, 32, 69, 38): '"""code"""'}, {}), "('code')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((123, 15, 123, 104), 'database.base.User', 'User', (), '', False, 'from database.base import User\n'), ((125, 8, 125, 33), 'database.base.db_session.add', 'base.db_session.add', ({(125, 28, 125, 32): 'user'}, {}), '(user)', False, 'from database import base\n'), ((126, 8, 126, 32), 'database.base.db_session.commit', 'base.db_session.commit', ({}, {}), '()', False, 'from database import base\n'), ((18, 8, 18, 35), 'database.base.db_session.query', 'base.db_session.query', ({(18, 30, 18, 34): 'User'}, {}), '(User)', False, 'from database import base\n'), ((27, 12, 27, 36), 'database.base.db_session.commit', 'base.db_session.commit', ({}, {}), '()', False, 'from database import base\n'), ((28, 12, 28, 70), 'flask.flash', 'flash', ({(28, 18, 28, 69): '"""귀하의 회원정보가 수정 되었습니다."""'}, {}), "('귀하의 회원정보가 수정 되었습니다.')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((29, 19, 29, 44), 'flask.redirect', 'redirect', ({(29, 28, 29, 43): '"""/auth/my_page"""'}, {}), "('/auth/my_page')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((35, 8, 35, 35), 'database.base.db_session.query', 'base.db_session.query', ({(35, 30, 35, 34): 'User'}, {}), '(User)', False, 'from database import base\n'), ((40, 27, 40, 43), 'flask_login.login_user', 'login_user', ({(40, 38, 40, 42): 'user'}, {}), '(user)', False, 'from flask_login import login_required, login_user, logout_user, current_user\n'), ((45, 12, 45, 76), 'flask.flash', 'flash', ({(45, 18, 45, 75): '"""비밀번호를 다시 확인하여 입력해주세요."""'}, {}), "('비밀번호를 다시 확인하여 입력해주세요.')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((62, 19, 62, 41), 'flask.redirect', 'redirect', ({(62, 28, 62, 40): 'redirect_url'}, {}), '(redirect_url)', False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((163, 23, 163, 29), 'database.base.User', 'User', ({}, {}), '()', False, 'from database.base import User\n'), ((169, 12, 169, 41), 'database.base.db_session.add', 'base.db_session.add', ({(169, 32, 169, 40): 'new_user'}, {}), '(new_user)', False, 'from database import base\n'), ((170, 12, 170, 36), 'database.base.db_session.commit', 'base.db_session.commit', ({}, {}), '()', False, 'from database import base\n'), ((171, 12, 171, 152), 'flask.flash', 'flash', ({(171, 18, 171, 151): '"""귀하는 회원가입이 성공적으로 완료되었습니다. 가입하신 정보로 로그인을 다시 하시기 바랍니다."""'}, {}), "('귀하는 회원가입이 성공적으로 완료되었습니다. 가입하신 정보로 로그인을 다시 하시기 바랍니다.')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((172, 19, 172, 42), 'flask.redirect', 'redirect', ({(172, 28, 172, 41): '"""/auth/login"""'}, {}), "('/auth/login')", False, 'from flask import Blueprint, redirect, render_template, request, flash, session\n'), ((121, 8, 121, 35), 'database.base.db_session.query', 'base.db_session.query', ({(121, 30, 121, 34): 'User'}, {}), '(User)', False, 'from database import base\n')]