# Copyright (C) 2005 JanRain, Inc.
# Copyright (C) 2009, 2010 Canonical Ltd
#
# 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 apache_openid.action import Action
from apache_openid.utils import add_cookie, get_cookies


class LogoutAction(Action):

    @property
    def external_cookie_names(self):
        try:
            return self.split_values(self.options.get('external-cookie-names'))
        except AssertionError:
            return []

    def do(self):
        self.clear_user_session()
        self.clear_external_cookies()
        redirect_url = self.options.get('external-logout-url')
        if redirect_url is None:
            return self.template.render('logout_page.html')
        else:
            self.response.redirect(redirect_url)

    def clear_user_session(self):
        try:
            del self.request.cookied_user
            del self.request.last_user
        except KeyError:
            pass

    def clear_external_cookies(self):
        """Clear any cookies from external apps which are defined in the config
        This is useful when the application protected by Apache OpenID doesn't
        provide a mechanism to log out of OpenID as well as itself.  Redirect
        requests for the application's logout URL should be handled by the
        OpenID logout handler.  The configuration should define the names of
        the application's cookies.  These will be deleted at the same time as
        the OpenID session.
        """
        cookies = get_cookies(self.request)
        for name in self.external_cookie_names:
            if ':' in name:
                path, name = name.split(':', 1)
            else:
                path = '/'
            if name in cookies:
                add_cookie(self.request, name, '', expires=0, path=path)

    def split_values(self, data):
        """Parse a string containing whitespace-separated team names."""
        assert data is not None
        values = []
        for s in data.split():
            val = s.strip()
            if not val or val[0] == '#':
                continue
            values.append(val)
        return values
