""" This is a test of the chain
    FileCatalogClient -> FileCatalogHandler -> FileCatalogDB

    It supposes that the DB is present, and that the service is running
"""

import unittest
import time


from DIRAC.Core.Base.Script import parseCommandLine
parseCommandLine()

from DIRAC.Resources.Catalog.FileCatalogClient import FileCatalogClient
from DIRAC.Core.Security.Properties import FC_MANAGEMENT
from DIRAC.Core.Security.ProxyInfo import getProxyInfo

import sys

seName = "mySE"
testUser = 'atsareg'
testGroup = 'dirac_user'
testDir = '/vo.formation.idgrilles.fr/user/a/atsareg/testdir'
parentDir = '/vo.formation.idgrilles.fr/user/a/atsareg'
parentparentDir = '/vo.formation.idgrilles.fr/user/a'
nonExistingDir = "/I/Dont/exist/dir"
testFile = '/vo.formation.idgrilles.fr/user/a/atsareg/testdir/testfile'
nonExistingFile = "/I/Dont/exist"

isAdmin = False
proxyUser = 'anon'
proxyGroup = 'anon'

class DFCTestCase(unittest.TestCase):

  def setUp( self ):
#     gLogger.setLevel( "DEBUG" )

    self.dfc = FileCatalogClient( "DataManagement/FileCatalog" )







class UserGroupCase( DFCTestCase ):

  def test_userOperations( self ):
    """Testing the user related operations
       If you are an admin, you should be allowed to, if not, it should fail

       CAUTION : THEY ARE DESIGNED FOR THE SecurityManager VOMSPolicy

    """

    expectedRes = None
    if isAdmin:
      print "Running UserTest in admin mode"
      expectedRes = True
    else:
      print "Running UserTest in non admin mode"
      expectedRes = False
  
    
    # Add the user
    result = self.dfc.addUser( testUser )
    self.assertEqual( result['OK'], expectedRes, "AddUser failed when adding new user: %s" % result )
    # Add an existing user
    result = self.dfc.addUser( testUser )
    self.assertEqual( result['OK'], expectedRes, "AddUser failed when adding existing user: %s" 
% result )
    # Fetch the list of user
    result = self.dfc.getUsers()
    self.assertEqual( result['OK'],
 expectedRes, "getUsers failed: %s" % result )

    if isAdmin:
      # Check if our user is present
      self.assertTrue( testUser in result['Value'], "getUsers failed: %s" % result )

    # remove the user we created
    result = self.dfc.deleteUser( testUser )
    self.assertEqual( result['OK'], expectedRes, "deleteUser failed: %s" % result )


  def test_groupOperations( self ):
    """Testing the group related operations
           If you are an admin, you should be allowed to, if not, it should fail

        CAUTION : THEY ARE DESIGNED FOR THE SecurityManager DirectorySecurityManagerWithDelete or VOMSPolicy
    """

    expectedRes = None
    if isAdmin:
      print "Running UserTest in admin mode"
      expectedRes = True
    else:
      print "Running UserTest in non admin mode"
      expectedRes = False

    # Create new group
    result = self.dfc.addGroup( testGroup )
    self.assertEqual( result['OK'], expectedRes, "AddGroup failed when adding new user: %s" % result )

    result = self.dfc.addGroup( testGroup )
    self.assertEqual( result['OK'], expectedRes, "AddGroup failed when adding existing user: %s" % result )

    result = self.dfc.getGroups()
    self.assertEqual( result['OK'], expectedRes, "getGroups failed: %s" % result )

    if isAdmin:
      self.assertTrue( testGroup in result['Value'] )

    result = self.dfc.deleteGroup( testGroup )
    self.assertEqual( result['OK'], expectedRes, "deleteGroup failed: %s" % result )




class FileCase( DFCTestCase ):

  def test_fileOperations( self ):
    """
      Tests the File related Operations
      CAUTION : THEY ARE DESIGNED FOR THE SecurityManager DirectorySecurityManagerWithDelete or VOMSPolicy

    """
    if isAdmin:
      print "Running UserTest in admin mode"
    else:
      print "Running UserTest in non admin mode"

    # Adding a new file
    result = self.dfc.addFile( { testFile: { 'PFN': 'testfilePFN',
                                         'SE': 'testSE' ,
                                         'Size':123,
                                         'GUID':'1000',
                                         'Checksum':'0' } } )
    self.assertTrue( result['OK'], "addFile failed when adding new file %s" % result )


    result = self.dfc.exists( testFile )
    self.assertTrue(result['OK'])
    self.assertEqual( result['Value'].get( 'Successful', {} ).get( testFile ),
                       testFile, "exists( testFile) should be the same lfn %s" % result )


    result = self.dfc.exists( {testFile:'1000'} )
    self.assertTrue(result['OK'])
    self.assertEqual( result['Value'].get( 'Successful', {} ).get( testFile ),
                       testFile, "exists( testFile : 1000) should be the same lfn %s" % result )

    result = self.dfc.exists( {testFile:{'GUID' : '1000', 'PFN' : 'blabla'}} )
    self.assertTrue(result['OK'])
    self.assertEqual( result['Value'].get( 'Successful', {} ).get( testFile ),
                       testFile, "exists( testFile : 1000) should be the same lfn %s" % result )

    # In fact, we don't check if the GUID is correct...
    result = self.dfc.exists( {testFile:'1001'} )
    self.assertTrue(result['OK'])
    self.assertEqual( result['Value'].get( 'Successful', {} ).get( testFile ),
                       testFile, "exists( testFile : 1001) should be the same lfn %s" % result )

    result = self.dfc.exists( {testFile + '2' : '1000'} )
    self.assertTrue(result['OK'])
    self.assertEqual( result['Value'].get( 'Successful', {} ).get( testFile + '2' ),
                       testFile, "exists( testFile2 : 1000) should return testFile %s" % result )



    # Re-adding the same file
    result = self.dfc.addFile( { testFile: { 'PFN': 'testfilePFN',
                                         'SE': 'testSE' ,
                                         'Size':123,
                                         'GUID':'1000',
                                         'Checksum':'0' } } )
    self.assertTrue( result["OK"], "addFile failed when adding existing file %s" % result )
    self.assertTrue( testFile in result["Value"]["Successful"], "addFile failed: it should  be possible to add an existing lfn with the same attributes %s" % result )

  # Re-adding the same file
    result = self.dfc.addFile( { testFile: { 'PFN': 'testfilePFN',
                                         'SE': 'testSE' ,
                                         'Size':123,
                                         'GUID':'1000',
                                         'Checksum':'1' } } )
    self.assertTrue( result["OK"], "addFile failed when adding existing file %s" % result )
    self.assertTrue( testFile in result["Value"]["Failed"], "addFile failed: it should not be possible to add an existing lfn with the different attributes %s" % result )


    # Re-adding the different LFN but same GUID
    result = self.dfc.addFile( { testFile + '2': { 'PFN': 'testfilePFN',
                                         'SE': 'testSE' ,
                                         'Size':123,
                                         'GUID':'1000',
                                         'Checksum':'0' } } )
    self.assertTrue( result["OK"], "addFile failed when adding non existing file with existing GUID %s" % result )
    self.assertTrue( testFile + '2' in result["Value"]["Failed"], "addFile failed: it should not be possible to add an existing GUID %s" % result )


    ##################################################################################
    # Setting existing status of existing file
    result = self.dfc.setFileStatus( {testFile:"AprioriGood"} )
    self.assertTrue( result["OK"], "setFileStatus failed when setting existing status of existing file %s" % result )
    self.assertTrue( testFile in result["Value"]["Successful"], "setFileStatus failed: %s should be in successful (%s)" % ( testFile, result ) )

    # Setting unexisting status of existing file
    result = self.dfc.setFileStatus( {testFile:"Happy"} )
    self.assertTrue( result["OK"], "setFileStatus failed when setting un-existing status of existing file %s" % result )
    self.assertTrue( testFile in result["Value"]["Failed"], "setFileStatus should have fai