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



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

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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 v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @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/INametag.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

interface INametag {
    function getByName(string memory name) external view returns (uint256);
    function ownerOf(uint256 tokenId) external view returns (address owner);
    function getTokenName(uint256 tokenId) external view returns (string memory);
}

// File: contracts/NametagWallet.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

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

contract NametagWallet is Ownable {
    event ContractAdded(address indexed nametagContract);
    event ContractRemoved(address indexed nametagContract);
    event NametagWalletChanged(address indexed owner, string indexed name, address wallet);

    bytes32 constant private TAIL = keccak256(".tag");

    address[] public nametagContracts;
    mapping(string => mapping(address => address)) internal nametagWallet;
    constructor(address[] memory addresses) {
        for (uint256 i = 0; i < addresses.length; ++i) {
            addNametagContract(addresses[i]);
        }
    }

    /**
     * @dev Adds new contract for looking for nametag
     */
    function addNametagContract(address _contract) public onlyOwner {
        nametagContracts.push(_contract);

        emit ContractAdded(_contract);
    }

    /**
     * @dev Removes the nametag contract
     */
    function removeNametagContract(address _contract) external onlyOwner {
        uint256 last = nametagContracts.length - 1;
        for (uint256 i = 0; i <= last; ++i) {
            if (nametagContracts[i] != _contract) continue;
            if (i != last) nametagContracts[i] = nametagContracts[last];
            nametagContracts.pop();
            emit ContractRemoved(_contract);
            return;
        }
        revert("NametagWallet: Contract not found");
    }

    /**
     * @dev Sets wallet for the nametag for sender. Nametag must be present on a contract.
     */
    function setNametagWallet(string calldata nametag, address wallet) external {
        require(wallet != address(0), "NametagWallet: Zero wallet address");

        _setNametagWallet(nametag, wallet);
    }

    /**
     * @dev Sets default wallet for the nametag for sender. Nametag must be present on a contract.
     */
    function clearNametagWallet(string calldata nametag) external {
        _setNametagWallet(nametag, address(0));
    }

    /**
     * @dev Returns the wallet address for the current owner of Nametag or just the owner's address
     */
    function getNametagWallet(string calldata nametag) external view returns (address wallet)  {
        (address _contract, uint256 tokenId, string memory name) = _resolveNametag(nametag);

        if (_contract == address(0)) return address(0);

        address owner = INametag(_contract).ownerOf(tokenId);
        wallet = nametagWallet[name][owner];

        if (wallet == address(0)) wallet = owner;
    }

    function _setNametagWallet(string calldata nametag, address wallet) private {
        require(bytes(nametag).length > 0, "NametagWallet: Nametag is empty");
        (address _contract,,string memory name) = _resolveNametag(nametag);
        require(_contract != address(0), "NametagWallet: Nametag not found");

        nametagWallet[name][_msgSender()] = wallet;

        emit NametagWalletChanged(_msgSender(), name, wallet);
    }

    function _resolveNametag(string calldata nametag) internal view returns (address, uint256, string memory) {
        string memory nametag2 = _getNametag(nametag);
        for (uint256 i = 0; i < nametagContracts.length; ++i) {
            address _contract = nametagContracts[i];
            uint256 tokenId = INametag(_contract).getByName(nametag2);
            if (tokenId != 0) {
                return (
                    _contract,
                    tokenId,
                    INametag(_contract).getTokenName(tokenId)
                );
            }
        }
        return (address(0), 0, "");
    }

    function _getNametag(string calldata nametag) private pure returns (string memory) {
        bytes calldata str = bytes(nametag);
        if (str.length >= 7) {
            bytes calldata a = str[str.length - 4 : str.length];
            if (keccak256(a) == TAIL) {
                return string(nametag[0 : str.length - 4]);
            }
        }

        return string(nametag);
    }
}