# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

from contextlib import contextmanager
import logging

from flask import current_app
from flask import make_response
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_classy import FlaskView
from xivo_auth_client import Client

from xivo_webi.auth import verify_token

from .forms import LoginAdminForm
from .webi import login_in_webi
from .webi import logout_from_webi


logger = logging.getLogger(__name__)


@contextmanager
def xivo_auth(config):
    yield Client(**config)


class LoginAdmin(FlaskView):

    def get(self):
        form = LoginAdminForm()
        session = request.cookies.get("x-auth-session")
        host = request.host

        if session:
            if current_app.config['webi']['enable']:
                if request.cookies.get("_eid"):
                    return redirect('https://{}'.format(host))
                else:
                    return render_template('login.html', form=form)

            return redirect('https://{}'.format(host))
        return render_template('login.html', form=form)

    def post(self):
        form = LoginAdminForm()

        if form.validate_on_submit():
            host = request.host
            current_app.config['auth']['username'] = form.username.data
            current_app.config['auth']['password'] = form.password.data

            with xivo_auth(current_app.config['auth']) as auth:
                token_data = auth.token.new('xivo_admin', expiration=3600)
                if not token_data:
                    return redirect(url_for('login_admin.LoginAdmin:get'))
                token = token_data['token']

            if token:
                redirect_to_index = redirect('https://{}'.format(host))
                response = make_response(redirect_to_index)
                response.set_cookie('x-auth-session', token)

                if current_app.config['webi']['enable']:
                    cookies = login_in_webi(form.username.data, form.password.data, current_app.config['webi']['host'])
                    if cookies:
                        response.set_cookie('_eid', cookies)

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


class LogoutAdmin(FlaskView):
    decorators = [verify_token]

    def get(self):
        session = request.cookies.get("x-auth-session")
        if current_app.config['webi']['enable']:
            eid = request.cookies.get("_eid")

        if session:
            if current_app.config['webi']['enable']:
                logout_from_webi(current_app.config['webi']['host'], eid, session)

            with xivo_auth(current_app.config['auth']) as auth:
                auth.token.revoke(session)

        response = redirect(url_for('login_admin.LoginAdmin:get'))
        response.set_cookie('x-auth-session', '', expires=0)

        if current_app.config['webi']['enable']:
            response.set_cookie('_eid', '', expires=0)

        return response
