contract CryptoBeastiesToken is ERC721Token, Ownable, ICryptoBeastiesToken { 
    using SafeMath for uint256;

    address proxyRegistryAddress;

    /**
    * @dev Constructor function
    * @param _storage address for Creature Storage
    * @param _uriPrefix string for url prefix
    */
    constructor(address _storage, string _uriPrefix) 
        ERC721Token("CryptoBeasties Token", "CRYB", _uriPrefix, _storage) public {
        proxyRegistryAddress = address(0);
    }

    /**
    * @dev Set a Proxy Registry Address, to be used by 3rd-party marketplaces.
    * @param _proxyRegistryAddress Address of the marketplace's proxy registry address
    */
    function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwnerOrController {
        proxyRegistryAddress = _proxyRegistryAddress;
    }

    /**
    * @dev Bulk load a number of tokens, as a way of reducing gas fees and migration time.
    * @param _tokenIds Array of tokenIds
    * @param _attributes Matching array of CryptoBeasties attributes
    * @param _owners Matching array of token owner addresses
    */
    function bulk(uint256[] _tokenIds, uint256[] _attributes, address[] _owners) external onlyOwnerOrController {
        for (uint index = 0; index < _tokenIds.length; index++) {
            ownedTokens[_owners[index]].push(_tokenIds[index]);
            tokenOwner[_tokenIds[index]] = _owners[index];
            emit Transfer(address(0), _owners[index], _tokenIds[index]);
        }
        cbStorage.storeBulk(_tokenIds, _attributes);
    }

    /**
    * @dev Create CryptoBeasties Token 
    * @param _tokenId ID of the new token
    * @param _attributes CryptoBeasties attributes
    * @param _owner address of the token owner
    */
    function create(uint256 _tokenId, uint256 _attributes, uint256[] _componentIds, address _owner) external onlyOwnerOrController {
        require(!super.exists(_tokenId));
        require(_owner != address(0));
        require(_attributes > 0); 
        super._mint(_owner, _tokenId);
        cbStorage.store(_tokenId, _attributes, _componentIds);
    }

   /**
   * Override isApprovedForAll to whitelist a 3rd-party marketplace's proxy accounts to enable gas-less listings.
   */
    function isApprovedForAll(
        address owner,
        address operator
    )
    public
    view
    returns (bool)
    {
        if (proxyRegistryAddress != address(0)) {
            ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
            if (proxyRegistry.proxies(owner) == operator) {
                return true;
            }
        }

        return super.isApprovedForAll(owner, operator);
    }

    /**
    * @dev List all token ids for a owner
    * @param _owner address of the token owner
    */
    function tokensOfOwner(address _owner) external view returns (uint256[]) {
        return ownedTokens[_owner];
    }
    
    /**
    * @dev List all token ids, an array of their attributes and an array componentIds (i.e. PowerStones)
    * @param _owner address for the given token ID
    */
    function getOwnedTokenData(
        address _owner
        ) 
        public 
        view 
        returns 
        (
            uint256[] tokens, 
            uint256[] attrs, 
            uint256[] componentIds, 
            bool[] isTransferable
        ) {

        uint256[] memory tokenIds = this.tokensOfOwner(_owner);
        uint256[] memory attribs = new uint256[](tokenIds.length);
        uint256[] memory firstCompIds = new uint256[](tokenIds.length);
        bool[] memory transferable = new bool[](tokenIds.length);
        
        uint256[] memory compIds;

        for (uint i = 0; i < tokenIds.length; i++) {
            (attribs[i], compIds) = cbStorage.getAttributes(tokenIds[i]);
            transferable[i] = this.isTransferable(tokenIds[i]);
            if (compIds.length > 0)
            {
                firstCompIds[i] = compIds[0];
            }
        }
        return (tokenIds, attribs, firstCompIds, transferable);
    }

    /**
    * @dev Get attributes and Component Ids (i.e. PowerStones) CryptoBeastie
    * @param _tokenId uint256 for the given token
    */
    function getProperties(uint256 _tokenId) external view returns (uint256 attrs, uint256[] compIds) {
        return cbStorage.getAttributes(_tokenId);
    }

    /**
    * @dev attributes and Component Ids (i.e. PowerStones) CryptoBeastie
    * @param _tokenId uint256 for the given token
    * @param _attributes Cryptobeasties attributes
    * @param _componentIds Array of Cryptobeasties componentIds (i.e. PowerStones)
    */
    function updateAttributes(uint256 _tokenId, uint256 _attributes, uint256[] _componentIds) external {
        require(ownerOf(_tokenId) == msg.sender || owner == msg.sender || isController(msg.sender)); //, "token owner"
        cbStorage.updateAttributes(_tokenId, _attributes, _componentIds);
    }

    /**
    * @dev Update the reference to the CryptoBeasties storage contract
    * @param _storage address for CryptoBeasties storage contract
    */
    function updateStorage(address _storage) external  onlyOwnerOrController {
        cbStorage = IEntityStorage(_storage);
    }

    /**
    * @dev List all of the CryptoBeasties token Ids held in the Storage Contract
    */
    function listTokens() external view returns (uint256[] tokens) {
        return cbStorage.list();
    }

    /**
    * @dev Update the URI prefix
    * @param _uriPrefix string for url prefix
    */
    function setURI(string _uriPrefix) external onlyOwnerOrController {
        uriPrefix = _uriPrefix;
    }

    /**
    * @dev Bulk setup of token Ids that can be transferred
    * @param _tokenIds array of token Ids that will be set for transfer
    */
    function bulkTransferable(uint256[] _tokenIds) external {
        address _owner = ownerOf(_tokenIds[0]);
        require(_owner == msg.sender || owner == msg.sender || isController(msg.sender)); //, "token owner"
        for (uint256 index = 0; index < _tokenIds.length; index++) {
            if (_owner == msg.sender) {
                require(ownerOf(_tokenIds[index]) == _owner); //, "token owner"
            } 
            transferableTokens.push(_tokenIds[index]);
        }
    }

    /**
    * @dev Set a Token Id that can be transfer
    * @param _tokenId Token Id that will be set for transfer
    */
    function setTransferable(uint256 _tokenId) external {
        require(ownerOf(_tokenId) == msg.sender || owner == msg.sender || isController(msg.sender)); //, "token owner"
        transferableTokens.push(_tokenId);
    }

    /**
    * @dev Bulk remove transferability of token Ids
    * @param _tokenIds array of token Ids that will be removed for transfer
    */
    function bulkRemoveTransferable(uint256[] _tokenIds) external {
        address _owner = ownerOf(_tokenIds[0]);
        require(_owner == msg.sender || owner == msg.sender || isController(msg.sender)); //, "token owner"
        for (uint256 index = 0; index < _tokenIds.length; index++) {
            if (_owner == msg.sender) {
                require(ownerOf(_tokenIds[index]) == _owner); //, "token owner"
            }
            _removeTransfer(_tokenIds[index]);
        }
    }

    /**
    * @dev A token Id that will be removed from transfer
    * @param _tokenId Token Id that will be removed for transfer
    */
    function removeTransferable(uint256 _tokenId) external {
        require(ownerOf(_tokenId) == msg.sender || owner == msg.sender || isController(msg.sender)); //, "token owner"
        _removeTransfer(_tokenId);
    }

    /**
    * @dev Internal function to remove transferability of a token Id
    * @param _tokenId Token Id that will be removed for Transfer
    */
    function _removeTransfer(uint256 _tokenId) internal {
        uint256 tokenIndex = 0;
        while (transferableTokens[tokenIndex] != _tokenId && tokenIndex < transferableTokens.length) {
            tokenIndex++;
        }

        // Reorg allTokens array
        uint256 lastTokenIndex = transferableTokens.length.sub(1);
        uint256 lastToken = transferableTokens[lastTokenIndex];

        transferableTokens[tokenIndex] = lastToken;
        transferableTokens[lastTokenIndex] = 0;

        transferableTokens.length--;
    }

    /**
    * @dev Support merging multiple tokens into one, to increase XP and level-up the target.
    * @param _mergeTokenIds Array of tokens to be removed and merged into the target
    * @param _targetTokenId The token whose attributes will be improved by the merge
    * @param _targetAttributes The new improved attributes for the target token
    */
    function mergeTokens(uint256[] _mergeTokenIds, uint256 _targetTokenId, uint256 _targetAttributes) external {
        address _owner = ownerOf(_targetTokenId);
        require(_owner == msg.sender || owner == msg.sender || isController(msg.sender)); //, "token owner"
        require(_mergeTokenIds.length > 0); //, "mergeTokens"
        require(!isTransferable(_targetTokenId)); // cannot target a token that is up for sale


        // remove merge material tokens
        for (uint256 index = 0; index < _mergeTokenIds.length; index++) {
            require(ownerOf(_mergeTokenIds[index]) == _owner); //, "array"
            _burn(_owner, _mergeTokenIds[index]);
        }

        // update target token
        uint256 attribs;
        uint256[] memory compIds;
        (attribs, compIds) = cbStorage.getAttributes(_targetTokenId);
        cbStorage.updateAttributes(_targetTokenId, _targetAttributes, compIds);
    }
}
/**
 * @title CryptoBeasties Full ERC721 Token
 * This implementation includes all the required and some optional functionality of the ERC721 standard,
 * plus references a separate storage contract for recording the game-specific data for each token. 
 * CryptoBeasties content and source code is Copyright (C) 2018 PlayStakes LLC, All rights reserved.
 */
function setURI(string _uriPrefix) external onlyOwnerOrController {
    uriPrefix = _uriPrefix;
}

/**
 * @dev Update the URI prefix
 * @param _uriPrefix string for url prefix
 */