##############################################################################
# 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.
##############################################################################

#
# test Team, the container and schema provider for Membership
#

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

from Products.CMFCore.utils import getToolByName

from TeamTestCase import *
from Products.TeamSpace.team import Team
from Products.TeamSpace.exceptions import MemberNotFound

try:
    set = set
except NameError:
    from sets import Set as set

class TestTeam(TeamTestCase):

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

    def test_AddRemoveMember(self):
        tmtool = self.tool
        tmtool.invokeFactory('Team', 'TEAM')
        tm = tmtool.getTeamById('TEAM')
        try:
            tm.addMember('NonExistent')
        except MemberNotFound:
            pass
        else:
            failUnless(1 == 0)
        from Products.CMFPlone.utils import _createObjectByType
        obj = _createObjectByType('Member', self.portal, 'Member')
        tm.addMember('Member')
        self.failUnless('Member' in tm.getMemberIds())
        tm.removeMember('Member')
        self.failIf('Member' in tm.getMemberIds())

    def test_SetGetActiveStates(self):
        tmtool = self.tool
        self.addAndPopulateTeam(TEAM_1)
        tm = tmtool.getTeamById(TEAM_1.id)
        act_states = ('published', 'visible',)
        tm.setActiveStates(act_states)
        self.assertEqual(tm.getActiveStates(), act_states)

    def test_SetGetAllowedTeamRoles(self):
        tmtool = self.tool
        self.addAndPopulateTeam(TEAM_1)
        tm = tmtool.getTeamById(TEAM_1.id)
        allowed_roles = ('Reviewer', 'Member',)
        tm.setAllowedTeamRoles(allowed_roles)
        self.assertEqual(tm.getAllowedTeamRoles(), allowed_roles)

    def test_getMemberships(self):
        tmtool = self.tool
        self.addAndPopulateTeam(TEAM_1)
        tm = tmtool.getTeamById(TEAM_1.id)
        mship_ids = [mship.id for mship in tm.getMemberships()]
        self.assertEqual(mship_ids.sort(), TEAM_1.getMemberIds().sort())

    def test_getMembershipsByStates(self):
        tmtool = self.tool
        self.addAndPopulateTeam(TEAM_1)
        tm = tmtool.getTeamById(TEAM_1.id)
        tm1_ids = TEAM_1.getMemberIds()
        tm1_ids.sort()
        wf_tool = self.portal.portal_workflow
        tm1_mships = tm.getMemberships()
        wf = wf_tool.getWorkflowsFor(tm1_mships[0])[0]
        init_state = wf.initial_state
        mems_in_state = tm.getMembershipsByStates( (init_state,) )
        memids_in_state = [m.id for m in mems_in_state]
        memids_in_state.sort()
        # should all be in initial state
        self.assertEqual(tm1_ids, memids_in_state)

        mem_ids_in_state = tm.getMemberIdsByStates( (init_state,) )
        mem_ids_in_state.sort()
        self.assertEqual(tm1_ids, mem_ids_in_state)
        
        m = mems_in_state[0]
        mid = m.id
        action = wf_tool.getActionsFor(m)[0]['id']
        wf_tool.doActionFor(m, action)
        # now the first member should not be in initial state
        new_state = wf_tool.getStatusOf(m.workflow_id, m)['review_state']
        mems_in_state = tm.getMembershipsByStates( (init_state,) )
        memids_in_state = [m.id for m in mems_in_state]
        memids_in_state.sort()
        self.assertNotEqual(tm1_ids, memids_in_state)

        mem_ids_in_state = tm.getMemberIdsByStates( (init_state,) )
        mem_ids_in_state.sort()
        self.assertNotEqual(tm1_ids, mem_ids_in_state)

        mems_in_state = tm.getMembershipsByStates( (new_state,) )
        memids_in_state = [m.id for m in mems_in_state]
        self.assertEqual(memids_in_state, [mid])

        mem_ids_in_state = tm.getMemberIdsByStates( (new_state,) )
        self.assertEqual(mem_ids_in_state, [mid])

    def test_getActiveMemberships(self):
        tmtool = self.tool
        wf_tool = self.portal.portal_workflow

        self.addAndPopulateTeam(TEAM_1)
        tm = tmtool.getTeamById(TEAM_1.id)
        tm1_ids = TEAM_1.getMemberIds()
        tm1_ids.sort()

        wf = wf_tool.getWorkflowById(tm.getMemberships()[0].workflow_id)
        init_state = wf.initial_state
        tm.setActiveStates( (init_state, ) )
        active_memids = [m.id for m in tm.getActiveMembers()]
        active_memids.sort()
        # all in initial state -> all active
        self.assertEqual(tm1_ids, active_memids)

        # Test convenience method too...
        active_mem_ids = tm.getActiveMemberIds()
        active_mem_ids.sort()
        self.assertEqual(tm1_ids, active_mem_ids)
         
        m = getattr(tm, tm1_ids[0])
        mid = m.id
        action = wf_tool.getActionsFor(m)[0]['id']
        wf_tool.doActionFor(m, action)
        new_state = wf_tool.getStatusOf(m.workflow_id, m)['review_state']
        active_memids = [m.id for m in tm.getActiveMembers()]
        self.failIf(mid in active_memids)

        active_mem_ids = tm.getActiveMemberIds()
        self.failIf(mid in active_mem_ids)

        tm.setActiveStates( (init_state, new_state,) )
        active_memids = [m.id for m in tm.getActiveMembers()]
        active_memids.sort()
        self.assertEqual(tm1_ids, active_memids)

        active_mem_ids = tm.getActiveMemberIds()
        active_mem_ids.sort()
        self.assertEqual(tm1_ids, active_mem_ids)

    def test_getMshipByIdActiveOnly(self):
        self.addAndPopulateTeam(TEAM_1)
        tm = self.tool.getTeamById(TEAM_1.id)
        mem_ids = TEAM_1.getMemberIds()
        mship = tm.getMembershipByMemberId(mem_ids[0])
        returned = tm.getMembershipByMemberId(mem_ids[0], active_only=True)
        self.failUnless(returned is None)
        
        wftool = getToolByName(self.portal, 'portal_workflow')
        wftool.doActionFor(mship, 'activate')
        returned = tm.getMembershipByMemberId(mem_ids[0], active_only=True)
        self.failUnless(returned == mship)

    def test_getMembers(self):
        self.addAndPopulateTeam(TEAM_1)
        tm = self.tool.getTeamById(TEAM_1.id)
        mems = tm.getMembers()

        mem_ids = TEAM_1.getMemberIds()
        right_mems = [self.portal._getOb(m_id) for m_id in mem_ids]
        self.assertEqual(set(mems), set(right_mems))

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

