# tasks_manager.py
import logging

logger = logging.getLogger('django')

class WalletPool:
    def __init__(self, redis_client, wallets):
        self.redis_client = redis_client
        self.pool = wallets
        for wallet in wallets:
            self.redis_client.set(wallet, 'UNLOCKED')
    
    def get_wallet(self):
        for wallet in self.pool:
            lock = self.redis_client.get(wallet)  
            logger.info(f"Trying to lock {wallet}, result: {lock}")  # sanity check
            if lock:
                if lock == "UNLOCKED":
                    self.redis_client.set(wallet, 'LOCKED')  
                    return wallet
            elif not self.redis_client.get(wallet):
                self.redis_client.set(wallet, 'LOCKED')  
                return wallet
        return None

    def release_wallet(self, wallet):
        self.redis_client.set(wallet, 'UNLOCKED')


"""
class BlockchainTasksManager:
    def __init__(self, num_threads=5):
        self.executor = ThreadPoolExecutor(max_workers=num_threads)
        wallet1 = {
            "walletAddress": settings.SELLTIX_WALLET,
            "privateKey": settings.SELLTIX_PRIVATE_KEY
        }
        wallet2 = {
            "walletAddress": settings.SELLTIX_WALLET2,
            "privateKey": settings.SELLTIX_PRIVATE_KEY2
        }
        wallet3 = {
            "walletAddress": settings.SELLTIX_WALLET3,
            "privateKey": settings.SELLTIX_PRIVATE_KEY3
        }
        wallet4 = {
            "walletAddress": settings.SELLTIX_WALLET4,
            "privateKey": settings.SELLTIX_PRIVATE_KEY4
        }

        wallet5 = {
            "walletAddress": settings.SELLTIX_WALLET5,
            "privateKey": settings.SELLTIX_PRIVATE_KEY5
        }
        self.wallets = [wallet1, wallet2, wallet3, wallet4, wallet5]
        self.wallet_locks = [threading.Lock() for _ in range(num_threads)]



    def execute_tasks(self, tasks):
        # Get the current thread number
        results = list(self.executor.map(self.blockchainJobManager, tasks))
        return results

    def blockchainJobManager(self, task):
        # Replace this with your actual task logic
        # Get the current thread number
        current_thread_number = threading.current_thread().ident % len(self.wallets)
        # Retrieve the corresponding wallet and lock for the current thread
        current_wallet = self.wallets[current_thread_number]
        current_wallet_lock = self.wallet_locks[current_thread_number]
        # Acquire the lock to ensure exclusive access to the wallet
        with current_wallet_lock:
            # Replace this with your actual task logic
            time.sleep(4)
            result = f"Task {task} executed by thread {current_thread_number} with wallet {current_wallet['walletAddress']} completed"

        return result
  
"""