contract CardOwnership is NFT, CardProto {

    // doing this strategy doesn't save gas
    // even setting the length to the max and filling in
    // unfortunately - maybe if we stop it boundschecking
    // address[] owners;
    mapping(uint => address) owners;
    mapping(uint => address) approved;
    // support multiple operators
    mapping(address => mapping(address => bool)) operators;

    // save space, limits us to 2^40 tokens (>1t)
    mapping(address => uint40[]) public ownedTokens;

    mapping(uint => string) uris;

    // save space, limits us to 2^24 tokens per user (~17m)
    uint24[] indices;

    uint public burnCount;

    /**
    * @return the name of this token
    */
    function name() public view returns (string) {
        return "Gods Unchained";
    }

    /**
    * @return the symbol of this token
    */  
    function symbol() public view returns (string) {
        return "GODS";
    }

    /**
    * @return the total number of cards in circulation
    */
    function totalSupply() public view returns (uint) {
        return cards.length - burnCount;
    }

    /**
    * @param to : the address to which the card will be transferred
    * @param id : the id of the card to be transferred
    */
    function transfer(address to, uint id) public payable {
        require(owns(msg.sender, id));
        require(isTradable(cards[id].proto));
        require(to != address(0));
        _transfer(msg.sender, to, id);
    }

    /**
    * internal transfer function which skips checks - use carefully
    * @param from : the address from which the card will be transferred
    * @param to : the address to which the card will be transferred
    * @param id : the id of the card to be transferred
    */
    function _transfer(address from, address to, uint id) internal {
        approved[id] = address(0);
        owners[id] = to;
        _addToken(to, id);
        _removeToken(from, id);
        emit Transfer(from, to, id);
    }

    /**
    * initial internal transfer function which skips checks and saves gas - use carefully
    * @param to : the address to which the card will be transferred
    * @param id : the id of the card to be transferred
    */
    function _create(address to, uint id) internal {
        owners[id] = to;
        _addToken(to, id);
        emit Transfer(address(0), to, id);
    }

    /**
    * @param to : the address to which the cards will be transferred
    * @param ids : the ids of the cards to be transferred
    */
    function transferAll(address to, uint[] ids) public payable {
        for (uint i = 0; i < ids.length; i++) {
            transfer(to, ids[i]);
        }
    }

    /**
    * @param proposed : the claimed owner of the cards
    * @param ids : the ids of the cards to check
    * @return whether proposed owns all of the cards 
    */
    function ownsAll(address proposed, uint[] ids) public view returns (bool) {
        for (uint i = 0; i < ids.length; i++) {
            if (!owns(proposed, ids[i])) {
                return false;
            }
        }
        return true;
    }

    /**
    * @param proposed : the claimed owner of the card
    * @param id : the id of the card to check
    * @return whether proposed owns the card
    */
    function owns(address proposed, uint id) public view returns (bool) {
        return ownerOf(id) == proposed;
    }

    /**
    * @param id : the id of the card
    * @return the address of the owner of the card
    */
    function ownerOf(uint id) public view returns (address) {
        return owners[id];
    }

    /**
    * @param id : the index of the token to burn
    */
    function burn(uint id) public {
        // require(isTradable(cards[id].proto));
        require(owns(msg.sender, id));
        burnCount++;
        // use the internal transfer function as the external
        // has a guard to prevent transfers to 0x0
        _transfer(msg.sender, address(0), id);
    }

    /**
    * @param ids : the indices of the tokens to burn
    */
    function burnAll(uint[] ids) public {
        for (uint i = 0; i < ids.length; i++){
            burn(ids[i]);
        }
    }

    /**
    * @param to : the address to approve for transfer
    * @param id : the index of the card to be approved
    */
    function approve(address to, uint id) public payable {
        require(owns(msg.sender, id));
        require(isTradable(cards[id].proto));
        approved[id] = to;
        emit Approval(msg.sender, to, id);
    }

    /**
    * @param to : the address to approve for transfer
    * @param ids : the indices of the cards to be approved
    */
    function approveAll(address to, uint[] ids) public payable {
        for (uint i = 0; i < ids.length; i++) {
            approve(to, ids[i]);
        }
    }

    /**
    * @param id : the index of the token to check
    * @return the address approved to transfer this token
    */
    function getApproved(uint id) public view returns(address) {
        return approved[id];
    }

    /**
    * @param owner : the address to check
    * @return the number of tokens controlled by owner
    */
    function balanceOf(address owner) public view returns (uint) {
        return ownedTokens[owner].length;
    }

    /**
    * @param id : the index of the proposed token
    * @return whether the token is owned by a non-zero address
    */
    function exists(uint id) public view returns (bool) {
        return owners[id] != address(0);
    }

    /**
    * @param to : the address to which the token should be transferred
    * @param id : the index of the token to transfer
    */
    function transferFrom(address from, address to, uint id) public payable {
        
        require(to != address(0));
        require(to != address(this));

        // TODO: why is this necessary
        // if you're approved, why does it matter where it comes from?
        require(ownerOf(id) == from);

        require(isSenderApprovedFor(id));

        require(isTradable(cards[id].proto));

        _transfer(ownerOf(id), to, id);
    }

    /**
    * @param to : the address to which the tokens should be transferred
    * @param ids : the indices of the tokens to transfer
    */
    function transferAllFrom(address to, uint[] ids) public payable {
        for (uint i = 0; i < ids.length; i++) {
            transferFrom(address(0), to, ids[i]);
        }
    }

    /**
     * @return the number of cards which have been burned
     */
    function getBurnCount() public view returns (uint) {
        return burnCount;
    }

    function isApprovedForAll(address owner, address operator) public view returns (bool) {
        return operators[owner][operator];
    }

    function setApprovalForAll(address to, bool toApprove) public {
        require(to != msg.sender);
        operators[msg.sender][to] = toApprove;
        emit ApprovalForAll(msg.sender, to, toApprove);
    }

    bytes4 constant magic = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));

    function safeTransferFrom(address from, address to, uint id, bytes data) public payable {
        require(to != address(0));
        transferFrom(from, to, id);
        if (_isContract(to)) {
            bytes4 response = ERC721TokenReceiver(to).onERC721Received.gas(50000)(from, id, data);
            require(response == magic);
        }
    }

    function safeTransferFrom(address from, address to, uint id) public payable {
        safeTransferFrom(from, to, id, "");
    }

    function _addToken(address to, uint id) private {
        uint pos = ownedTokens[to].push(uint40(id)) - 1;
        indices.push(uint24(pos));
    }

    function _removeToken(address from, uint id) public payable {
        uint24 index = indices[id];
        uint lastIndex = ownedTokens[from].length - 1;
        uint40 lastId = ownedTokens[from][lastIndex];

        ownedTokens[from][index] = lastId;
        ownedTokens[from][lastIndex] = 0;
        ownedTokens[from].length--;
    }

    function isSenderApprovedFor(uint256 id) internal view returns (bool) {
        return owns(msg.sender, id) || getApproved(id) == msg.sender || isApprovedForAll(ownerOf(id), msg.sender);
    }

    function _isContract(address test) internal view returns (bool) {
        uint size; 
        assembly {
            size := extcodesize(test)
        }
        return (size > 0);
    }

    function tokenURI(uint id) public view returns (string) {
        return uris[id];
    }
    
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId){
        return ownedTokens[owner][index];
    }

    function tokenByIndex(uint256 index) external view returns (uint256){
        return index;
    }

    function supportsInterface(bytes4 interfaceID) public view returns (bool) {
        return (
            interfaceID == this.supportsInterface.selector || // ERC165
            interfaceID == 0x5b5e139f || // ERC721Metadata
            interfaceID == 0x6466353c || // ERC-721 on 3/7/2018
            interfaceID == 0x780e9d63
        ); // ERC721Enumerable
    }

    function implementsERC721() external pure returns (bool) {
        return true;
    }

    function getOwnedTokens(address user) public view returns (uint40[]) {
        return ownedTokens[user];
    }
    

}
function name() public view returns (string) {
    return "Gods Unchained";
}

/**
 * @return the name of this token
 */