contract DungeonToken is ERC721, DungeonStructs, Pausable, JointOwnable {

    /**
     * @notice Limits the number of dungeons the contract owner can ever create.
     */
    uint public constant DUNGEON_CREATION_LIMIT = 1024;

    /**
     * @dev The Mint event is fired whenever a new dungeon is created.
     */
    event Mint(address indexed owner, uint newTokenId, uint difficulty, uint seedGenes);

    /**
     * @dev The NewDungeonFloor event is fired whenever a new dungeon floor is added.
     */
    event NewDungeonFloor(uint timestamp, uint indexed dungeonId, uint32 newFloorNumber, uint128 newRewards , uint newFloorGenes);

    /**
     * @dev Transfer event as defined in current draft of ERC721. Emitted every time a token
     *  ownership (Dungeon Master) is assigned, including token creation.
     */
    event Transfer(address indexed from, address indexed to, uint tokenId);

    /**
     * @dev Name of token.
     */
    string public constant name = "Dungeon";

    /**
     * @dev Symbol of token.
     */
    string public constant symbol = "DUNG";

    /**
     * @dev An array containing the Dungeon struct, which contains all the dungeons in existance.
     *  The ID for each dungeon is the index of this array.
     */
    Dungeon[] public dungeons;

    /**
     * @dev A mapping from token IDs to the address that owns them.
     */
    mapping(uint => address) tokenIndexToOwner;

    /**
     * @dev A mapping from owner address to count of tokens that address owns.
     */
    mapping(address => uint) ownershipTokenCount;

    /**
     * Each non-fungible token owner can own more than one token at one time.
     * Because each token is referenced by its unique ID, however,
     * it can get difficult to keep track of the individual tokens that a user may own.
     * To do this, the contract keeps a record of the IDs of each token that each user owns.
     */
    mapping(address => uint[]) public ownerTokens;

    /**
     * @notice Returns the total number of tokens currently in existence.
     */
    function totalSupply() public view returns (uint) {
        return dungeons.length;
    }

    /**
     * @notice Returns the number of tokens owned by a specific address.
     * @param _owner The owner address to check.
     */
    function balanceOf(address _owner) public view returns (uint) {
        return ownershipTokenCount[_owner];
    }

    /**
     * @dev Checks if a given address is the current owner of a particular token.
     * @param _claimant The address we are validating against.
     * @param _tokenId Token ID
     */
    function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
        return tokenIndexToOwner[_tokenId] == _claimant;
    }

    /**
     * @notice Returns the address currently assigned ownership of a given token.
     */
    function ownerOf(uint _tokenId) external view returns (address) {
        require(tokenIndexToOwner[_tokenId] != address(0));

        return tokenIndexToOwner[_tokenId];
    }

    /**
     * @dev Assigns ownership of a specific token to an address.
     */
    function _transfer(address _from, address _to, uint _tokenId) internal {
        // Increment the ownershipTokenCount.
        ownershipTokenCount[_to]++;

        // Transfer ownership.
        tokenIndexToOwner[_tokenId] = _to;

        // Add the _tokenId to ownerTokens[_to]
        ownerTokens[_to].push(_tokenId);

        // When creating new token, _from is 0x0, but we can't account that address.
        if (_from != address(0)) {
            ownershipTokenCount[_from]--;

            // Remove the _tokenId from ownerTokens[_from]
            uint[] storage fromTokens = ownerTokens[_from];
            bool iFound = false;

            for (uint i = 0; i < fromTokens.length - 1; i++) {
                if (iFound) {
                    fromTokens[i] = fromTokens[i + 1];
                } else if (fromTokens[i] == _tokenId) {
                    iFound = true;
                }
            }
        }

        // Emit the Transfer event.
        Transfer(_from, _to, _tokenId);
    }

    /**
     * @notice External function to transfers a token to another address.
     * @param _to The address of the recipient, can be a user or contract.
     * @param _tokenId The ID of the token to transfer.
     */
    function transfer(address _to, uint _tokenId) whenNotPaused external {
        // Safety check to prevent against an unexpected 0x0 default.
        require(_to != address(0));

        // Disallow transfers to this contract to prevent accidental misuse.
        require(_to != address(this));

        // You can only send your own token.
        require(_owns(msg.sender, _tokenId));

        // Reassign ownership, clear pending approvals, emit Transfer event.
        _transfer(msg.sender, _to, _tokenId);
    }

    /**
     * @dev The external function that creates a new dungeon and stores it, only contract owners
     *  can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
     *  Will generate a Mint event, a  NewDungeonFloor event, and a Transfer event.
     * @param _difficulty The difficulty of the new dungeon.
     * @param _seedGenes The seed genes of the new dungeon.
     * @return The dungeon ID of the new dungeon.
     */
    function createDungeon(uint _difficulty, uint _seedGenes, address _owner) eitherOwner external returns (uint) {
        // Ensure the total supply is within the fixed limit.
        require(totalSupply() < DUNGEON_CREATION_LIMIT);

        // UPDATE STORAGE
        // Create a new dungeon.
        dungeons.push(Dungeon(uint32(now), 0, uint16(_difficulty), 0, 0, 0, _seedGenes, 0));

        // Token id is the index in the storage array.
        uint newTokenId = dungeons.length - 1;

        // Emit the token mint event.
        Mint(_owner, newTokenId, _difficulty, _seedGenes);

        // Initialize the fist floor with using the seedGenes, this will emit the NewDungeonFloor event.
        addDungeonNewFloor(newTokenId, 0, _seedGenes);

        // This will assign ownership, and also emit the Transfer event.
        _transfer(0, _owner, newTokenId);

        return newTokenId;
    }

    /**
     * @dev The external function to set dungeon status by its ID,
     *  refer to DungeonStructs for more information about dungeon status.
     *  Only contract owners can alter dungeon state.
     */
    function setDungeonStatus(uint _id, uint _newStatus) eitherOwner external {
        require(_id < totalSupply());

        dungeons[_id].status = uint16(_newStatus);
    }

    /**
     * @dev The external function to add additional dungeon rewards by its ID,
     *  only contract owners can alter dungeon state.
     */
    function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner external {
        require(_id < totalSupply());

        dungeons[_id].rewards += uint64(_additinalRewards);
    }

    /**
     * @dev The external function to add another dungeon floor by its ID,
     *  only contract owners can alter dungeon state.
     *  Will generate both a NewDungeonFloor event.
     */
    function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner public {
        require(_id < totalSupply());

        Dungeon storage dungeon = dungeons[_id];

        dungeon.floorNumber++;
        dungeon.floorCreationTime = uint32(now);
        dungeon.rewards = uint128(_newRewards);
        dungeon.floorGenes = _newFloorGenes;

        // Emit the NewDungeonFloor event.
        NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes);
    }

}
/**
 * @title The ERC-721 compliance token contract for the Dungeon tokens.
 * @dev See the DungeonStructs contract to see the details of the Dungeon token data structure.
 */
function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner external {
    require(_id < totalSupply());

    dungeons[_id].rewards += uint64(_additinalRewards);
}

/**
 * @dev The external function to add additional dungeon rewards by its ID,
 *  only contract owners can alter dungeon state.
 */