// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.21;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: contracts/KeyPoster.sol



// SPDX-License-Identifier: Unlicense

//  __   ___    _____  __      __  _____      ____      _____   ________    _____   ______
// () ) / __)  / ___/  ) \    / ( (  __ \    / __ \    / ____\ (___  ___)  / ___/  (   __ \
// ( (_/ /    ( (__     \ \  / /   ) )_) )  / /  \ \  ( (___       ) )    ( (__     ) (__) )
// ()   (      ) __)     \ \/ /   (  ___/  ( ()  () )  \___ \     ( (      ) __)   (    __/
// () /\ \    ( (         \  /     ) )     ( ()  () )      ) )     ) )    ( (       ) \ \  _
// ( (  \ \    \ \___      )(     ( (       \ \__/ /   ___/ /     ( (      \ \___  ( ( \ \_))
// ()_)  \_\    \____\    /__\    /__\       \____/   /____/      /__\      \____\  )_) \__/

pragma solidity ^0.8.21;

import "@openzeppelin/contracts/access/Ownable.sol";

/**************************************************************************
 * @dev KeyPoster is a simple contract that stores an array of addresses. *
 * @dev The contract uses the term "Key" in place of Address in order to  *
 * @dev avoid confusion from solidity functions. Keys can only be added   *
 * @dev or removed by the contract owner. The contract has a function to  *
 * @dev transfer ownership. Anybody can check if an address (key) is in   *
 * @dev the list (returns bool) or may call a complete list of keys       *
 * @dev stored. A key is also stored with the block number the key was    *
 * @dev added. License is Unlicense, open source and free to use.         *
 *************************************************************************/

contract KeyPoster is Ownable {
    // Mapping to keep track of keys
    mapping(address => bool) private _keys;
    mapping(address => uint256) private _keyBlockNumbers;

    // Array to store all keys for efficient retrieval
    address[] private _allKeys;

    // Events
    event KeyAdded(address indexed key, uint256 blockNumber);
    event KeyRemoved(address indexed key);

    struct KeyData {
        address key;
        uint256 blockNumber;
    }

    /**
     * @dev Constructor that sets the initial owner.
     * @param initialOwner The initial owner's address.
     */
    constructor(address initialOwner) Ownable(initialOwner) {}

    /**
     * @dev Internal function to determine if an address is a contract.
     * @param addr The address to check.
     * @return bool True if the address is a contract, otherwise false.
     */
    function _isContract(address addr) internal view returns (bool) {
        uint256 size;
        assembly {
            size := extcodesize(addr)
        }
        return size > 0;
    }

    /**
     * @dev Add a Key.
     * Only callable by the owner.
     * Validates that the key is not a contract address.
     * @param key The Key to add.
     */
    function addKey(address key) external onlyOwner {
        require(!_keys[key], "Key already exists");
        require(!_isContract(key), "Key cannot be a contract address");
        _keys[key] = true;
        _keyBlockNumbers[key] = block.number;
        _allKeys.push(key);
        emit KeyAdded(key, block.number);
    }

    /**
     * @dev Remove a Key.
     * Only callable by the owner.
     * @param key The Key to remove.
     */
    function removeKey(address key) external onlyOwner {
        require(_keys[key], "Key does not exist");
        _keys[key] = false;

        // Remove the key from _allKeys array
        for (uint256 i = 0; i < _allKeys.length; i++) {
            if (_allKeys[i] == key) {
                _allKeys[i] = _allKeys[_allKeys.length - 1];
                _allKeys.pop();
                break;
            }
        }
        emit KeyRemoved(key);
    }

    /**
     * @dev Check if a Key exists.
     * @param key The Key to check.
     * @return bool True if the Key exists, otherwise false.
     */
    function isKey(address key) external view returns (bool) {
        return _keys[key];
    }

    /**
     * @dev Retrieve all Keys along with the block numbers they were added.
     * @return KeyData[] The list of all Keys and their block numbers.
     */
    function getAllKeys() external view returns (KeyData[] memory) {
        KeyData[] memory keysWithBlockNumbers = new KeyData[](_allKeys.length);
        for (uint256 i = 0; i < _allKeys.length; i++) {
            keysWithBlockNumbers[i] = KeyData(
                _allKeys[i],
                _keyBlockNumbers[_allKeys[i]]
            );
        }
        return keysWithBlockNumbers;
    }
}

// File: contracts/KeyPosterFactory.sol



// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.21;

import "./KeyPoster.sol";

contract KeyPosterFactory {
    event KeyPosterCreated(address indexed newKeyPoster, address indexed owner);

    function createKeyPoster() public returns (address) {
        KeyPoster newKeyPoster = new KeyPoster(msg.sender);
        emit KeyPosterCreated(address(newKeyPoster), msg.sender);
        return address(newKeyPoster);
    }
}