##############################################################################
# Copyright (c) 2004-2005 Black Rock City, LLC
# Copyright (c) 2004-2005 ObjectRealms, LLC
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
"""
$Id: $
"""
#
# test Team Roster
#

import os, sys
if __name__ == '__main__':
    execfile(os.path.join(sys.path[0], 'framework.py'))


from AccessControl import getSecurityManager
from TeamTestCase import *

ID_SORT_ATTRIBUTE = 'getId'

class TestTeamRoster(TeamTestCase):

    def afterSetUp(self):
        TeamTestCase.afterSetUp(self)

        tmtool = self.tool
        self.addAndPopulateTeam(TEAM_1, add_roles=1)
        self.team = tmtool.getTeamById(TEAM_1.id)

        # make a team space
        self.portal.portal_types.constructContent('TeamSpace',
                                                  self.folder,
                                                  'teamspace1')
        self.team_space = getattr(self.folder, 'teamspace1')

        # Associate the space with the team
        self.team_space.setSpaceTeams([self.team])

        # add a roster to the space
        self.portal.portal_types.constructContent('TeamRoster',
                                                  self.team_space,
                                                  TEAM_1.id)
        self.team_roster = getattr(self.team_space, TEAM_1.id)

        # Associate Roster to Team
        self.team_roster.setTeams([self.team])

        self.wf_tool = self.portal.portal_workflow

    def activateAllTeamMembers(self, team):
        for m in team.getMemberships():
            self.wf_tool.doActionFor(m, 'activate')

    def getRosterSearchResults(self, **kw):
        """ grab members using the roster search """
        roster_results = self.team_roster.rosterSearchResults(sort_on=ID_SORT_ATTRIBUTE,
                                                              **kw)
        roster_results = [ result.getId for result in roster_results ]
        return roster_results

    def test_teamRoster(self):
        # Get the member ids of the team
        tm1_ids = TEAM_1.getMemberIds()
        tm1_ids.sort()
        wf_tool = self.wf_tool

        #get the memberships of the teams
        tm1_mships = self.team.getMemberships()

        # get the workflow of the memberships
        wf = wf_tool.getWorkflowsFor(tm1_mships[0])[0]

        # get the ids for the memberships
        mem_ids = [m.getId() for m in tm1_mships]

        # activate all tm memberships
        self.activateAllTeamMembers(self.team)
        roster_results = self.getRosterSearchResults()

        self.assertEqual(tm1_ids, roster_results)

        # deactivate one member
        pmship = tm1_mships[0]
        wf_tool.doActionFor(pmship, 'deactivate')

        active_member_ids = self.team_roster.getActiveMemberIds()
        self.failIf(tm1_mships[0].getId() in active_member_ids)

        roster_results = self.getRosterSearchResults()
        self.failIf(tm1_mships[0].getId() in roster_results)

    def test_teamRosterSecurity(self):
        tm1_mships = self.team.getMemberships()
        pmem = tm1_mships[0].getMember()
        
        wf_tool = self.wf_tool
        wf = wf_tool.getWorkflowsFor(pmem)[0]

        self.activateAllTeamMembers(self.team)
        # make one member private
        transition_ids = [t['id'] for t in wf_tool.getTransitionsFor(pmem)]
        if 'make_private' in transition_ids:
            wf_tool.doActionFor(pmem, 'make_private')
        elif 'hide' in transition_ids:
            wf_tool.doActionFor(pmem, 'hide')

        # log in as the other member
        self.login(tm1_mships[1].id)

        # we shouldn't see the private member
        roster_batch = self.team_roster.ts_team_get_members()
        self.failIf(pmem in roster_batch)
        self.failUnless(tm1_mships[1].getMember() in roster_batch)

    def test_rosterTeamVocabulary(self):
        # add a second team
        self.addAndPopulateTeam(TEAM_2, add_roles=1)
        tm2 = self.tool.getTeamById(TEAM_2.id)

        # now our roster vocab should NOT include team 2 in its vocab
        tms_field = self.team_roster.Schema()['assoc_teams']
        vocab = tms_field.Vocabulary(self.team_roster)
        self.failIf(tm2.UID() in vocab.keys())
        self.failUnless(self.team.UID() in vocab.keys())

        # add a roster outside of a teamspace context
        self.portal.invokeFactory('TeamRoster', 'roster2')
        r2 = self.portal.roster2
        vocab = tms_field.Vocabulary(r2)
        self.failUnless(tm2.UID() in vocab.keys() and \
                        self.team.UID() in vocab.keys())
        

if __name__ == '__main__':
    framework()
else:
    from unittest import TestSuite, makeSuite
    def test_suite():
        suite = TestSuite()
        suite.addTest(makeSuite(TestTeamRoster))
        return suite

