contract SaleBase is OperationalControl, ERC721Holder {
    using SafeMath for uint256;
    
    /// EVENTS 

    event SaleCreated(uint256 tokenID, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt);
    event TeamSaleCreated(uint256[9] tokenIDs, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt);
    event SaleWinner(uint256 tokenID, uint256 totalPrice, address winner);
    event TeamSaleWinner(uint256[9] tokenIDs, uint256 totalPrice, address winner);
    event SaleCancelled(uint256 tokenID, address sellerAddress);
    event EtherWithdrawed(uint256 value);

    /// STORAGE

    /**
     * @dev        Represents an Sale on MLB CryptoBaseball (ERC721)
     */
    struct Sale {
        // Current owner of NFT (ERC721)
        address seller;
        // Price (in wei) at beginning of sale
        uint256 startingPrice;
        // Price (in wei) at end of sale
        uint256 endingPrice;
        // Duration (in seconds) of sale
        uint256 duration;
        // Time when sale started
        // NOTE: 0 if this sale has been concluded
        uint256 startedAt;
        // ERC721 AssetID
        uint256[9] tokenIds;
    }

    /**
     * @dev        Reference to contract tracking ownership & asset details
     */
    MLBNFT public nonFungibleContract;

    // Cut owner takes on each sale, measured in basis points (1/100 of a percent).
    // Values 0-10,000 map to 0%-100%
    uint256 public ownerCut = 500; //5%

    // Map from token to their corresponding sale.
    mapping (uint256 => Sale) tokenIdToSale;

    /**
     * @dev        Returns true if the claimant owns the token.
     * @param      _claimant  The claimant
     * @param      _tokenId   The token identifier
     */
    function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
        return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
    }

    /**
     * @dev        Internal function to ESCROW
     * @notice     Escrows the ERC721 Token, assigning ownership to this contract. Throws if the escrow fails.
     * @param      _owner    The owner
     * @param      _tokenId  The token identifier
     */
    function _escrow(address _owner, uint256 _tokenId) internal {
        nonFungibleContract.safeTransferFrom(_owner, this, _tokenId);
    }

    /**
     * @dev        Internal Transfer function
     * @notice     Transfers an ERC721 Token owned by this contract to another address. Returns true if the transfer succeeds.
     * @param      _owner     The owner
     * @param      _receiver  The receiver
     * @param      _tokenId   The token identifier
     */
    function _transfer(address _owner, address _receiver, uint256 _tokenId) internal {
        nonFungibleContract.transferFrom(_owner, _receiver, _tokenId);
    }

    /**
     * @dev        Internal Function to add Sale, which duration check (atleast 1 min duration required)
     * @notice     Adds an sale to the list of open sales. Also fires the SaleCreated event.
     * @param      _tokenId  The token identifier
     * @param      _sale     The sale
     */
    function _addSale(uint256 _tokenId, Sale _sale) internal {
        // Require that all sales have a duration of
        // at least one minute.
        require(_sale.duration >= 1 minutes);
        
        tokenIdToSale[_tokenId] = _sale;

        emit SaleCreated(
            uint256(_tokenId),
            uint256(_sale.startingPrice),
            uint256(_sale.endingPrice),
            uint256(_sale.duration),
            uint256(_sale.startedAt)
        );
    }

    /**
     * @dev        Internal Function to add Team Sale, which duration check (atleast 1 min duration required)
     * @notice     Adds an sale to the list of open sales. Also fires the SaleCreated event.
     * @param      _tokenIds  The token identifiers
     * @param      _sale      The sale
     */
    function _addTeamSale(uint256[9] _tokenIds, Sale _sale) internal {
        // Require that all sales have a duration of
        // at least one minute.
        require(_sale.duration >= 1 minutes);
        
        for(uint ii = 0; ii < 9; ii++) {
            require(_tokenIds[ii] != 0);
            require(nonFungibleContract.exists(_tokenIds[ii]));

            tokenIdToSale[_tokenIds[ii]] = _sale;
        }

        emit TeamSaleCreated(
            _tokenIds,
            uint256(_sale.startingPrice),
            uint256(_sale.endingPrice),
            uint256(_sale.duration),
            uint256(_sale.startedAt)
        );
    }

    /**
     * @dev        Facilites Sale cancellation. Also removed the Sale from the array
     * @notice        Cancels an sale (given the collectibleID is not 0). SaleCancelled Event
     * @param      _tokenId  The token identifier
     * @param      _seller   The seller
     */
    function _cancelSale(uint256 _tokenId, address _seller) internal {
        Sale memory saleItem = tokenIdToSale[_tokenId];

        //Check for team sale
        if(saleItem.tokenIds[1] != 0) {
            for(uint ii = 0; ii < 9; ii++) {
                _removeSale(saleItem.tokenIds[ii]);
                _transfer(address(this), _seller, saleItem.tokenIds[ii]);
            }
            emit SaleCancelled(_tokenId, _seller);
        } else {
            _removeSale(_tokenId);
            _transfer(address(this), _seller, _tokenId);
            emit SaleCancelled(_tokenId, _seller);
        }
    }

    /**
     * @dev        Computes the price and transfers winnings. Does NOT transfer ownership of token.
     * @param      _tokenId    The token identifier
     * @param      _bidAmount  The bid amount
     */
    function _bid(uint256 _tokenId, uint256 _bidAmount)
        internal
        returns (uint256)
    {
        // Get a reference to the sale struct
        Sale storage _sale = tokenIdToSale[_tokenId];
        uint256[9] memory tokenIdsStore = tokenIdToSale[_tokenId].tokenIds;
        // Explicitly check that this sale is currently live.
        // (Because of how Ethereum mappings work, we can't just count
        // on the lookup above failing. An invalid _tokenId will just
        // return an sale object that is all zeros.)
        require(_isOnSale(_sale));

        // Check that the bid is greater than or equal to the current price
        uint256 price = _currentPrice(_sale);
        require(_bidAmount >= price);

        // Grab a reference to the seller before the sale  struct
        // gets deleted.
        address seller = _sale.seller;

        if(tokenIdsStore[1] > 0) {
            for(uint ii = 0; ii < 9; ii++) {
                // The bid is good! Remove the sale before sending the fees
                // to the sender so we can't have a reentrancy attack.
                _removeSale(tokenIdsStore[ii]);
            }
        } else {
            // The bid is good! Remove the sale before sending the fees
            // to the sender so we can't have a reentrancy attack.
            _removeSale(_tokenId);
        }

        

        // Transfer proceeds to seller (if there are any!)
        if (price > 0) {
            // Calculate the marketplace's cut.
            // (NOTE: _computeCut() is guaranteed to return a
            // value <= price, so this subtraction can't go negative.)
            uint256 marketsCut = _computeCut(price);
            uint256 sellerProceeds = price.sub(marketsCut);

            // NOTE: Doing a transfer() in the middle of a complex
            // method like this is generally discouraged because of
            // reentrancy attacks and DoS attacks if the seller is
            // a contract with an invalid fallback function. We explicitly
            // guard against reentrancy attacks by removing the sale
            // before calling transfer(), and the only thing the seller
            // can DoS is the sale of their own asset! (And if it's an
            // accident, they can call cancelSale(). )
            seller.transfer(sellerProceeds);
        }

        // Calculate any excess funds included with the bid. If the excess
        // is anything worth worrying about, transfer it back to bidder.
        // NOTE: We checked above that the bid amount is greater than or
        // equal to the price so this cannot underflow.
        uint256 bidExcess = _bidAmount.sub(price);

        // Return the funds. Similar to the previous transfer, this is
        // not susceptible to a re-entry attack because the sale is
        // removed before any transfers occur.
        msg.sender.transfer(bidExcess);

        // Tell the world!
        // uint256 assetID, uint256 totalPrice, address winner, uint16 generation
        if(tokenIdsStore[1] > 0) {
            emit TeamSaleWinner(tokenIdsStore, price, msg.sender);
        } else {
            emit SaleWinner(_tokenId, price, msg.sender);
        }
        
        return price;
    }

    /**
     * @dev        Removes an sale from the list of open sales.
     * @param      _tokenId  The token identifier
     */
    function _removeSale(uint256 _tokenId) internal {
        delete tokenIdToSale[_tokenId];
    }

    /**
     * @dev        Returns true if the FT (ERC721) is on sale.
     * @param      _sale  The sale
     */
    function _isOnSale(Sale memory _sale) internal pure returns (bool) {
        return (_sale.startedAt > 0);
    }

    /** @dev Returns current price of an FT (ERC721) on sale. Broken into two
     *  functions (this one, that computes the duration from the sale
     *  structure, and the other that does the price computation) so we
     *  can easily test that the price computation works correctly.
     */
    function _currentPrice(Sale memory _sale)
        internal
        view
        returns (uint256)
    {
        uint256 secondsPassed = 0;

        // A bit of insurance against negative values (or wraparound).
        // Probably not necessary (since Ethereum guarnatees that the
        // now variable doesn't ever go backwards).
        if (now > _sale.startedAt) {
            secondsPassed = now - _sale.startedAt;
        }

        return _computeCurrentPrice(
            _sale.startingPrice,
            _sale.endingPrice,
            _sale.duration,
            secondsPassed
        );
    }

    /** @dev Computes the current price of an sale. Factored out
     *  from _currentPrice so we can run extensive unit tests.
     *  When testing, make this function public and turn on
     *  `Current price computation` test suite.
     */
    function _computeCurrentPrice(
        uint256 _startingPrice,
        uint256 _endingPrice,
        uint256 _duration,
        uint256 _secondsPassed
    )
        internal
        pure
        returns (uint256)
    {
        // NOTE: We don't use SafeMath (or similar) in this function because
        //  all of our public functions carefully cap the maximum values for
        //  time (at 64-bits) and currency (at 128-bits). _duration is
        //  also known to be non-zero (see the require() statement in
        //  _addSale())
        if (_secondsPassed >= _duration) {
            // We've reached the end of the dynamic pricing portion
            // of the sale, just return the end price.
            return _endingPrice;
        } else {
            // Starting price can be higher than ending price (and often is!), so
            // this delta can be negative.
            int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);

            // This multiplication can't overflow, _secondsPassed will easily fit within
            // 64-bits, and totalPriceChange will easily fit within 128-bits, their product
            // will always fit within 256-bits.
            int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);

            // currentPriceChange can be negative, but if so, will have a magnitude
            // less that _startingPrice. Thus, this result will always end up positive.
            int256 currentPrice = int256(_startingPrice) + currentPriceChange;

            return uint256(currentPrice);
        }
    }

    /**
     * @dev        Computes owner's cut of a sale.
     * @param      _price  The price
     */
    function _computeCut(uint256 _price) internal view returns (uint256) {
        // NOTE: We don't use SafeMath (or similar) in this function because
        //  all of our entry functions carefully cap the maximum values for
        //  currency (at 128-bits), and ownerCut <= 10000 (see the require()
        //  statement in the CSLClockSales constructor). The result of this
        //  function is always guaranteed to be <= _price.
        return _price.mul(ownerCut.div(10000));
    }
}
/* Contains models, variables, and internal methods for the ERC-721 sales.
 * @title Sale Base
 * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
 */
function _computeCut(uint256 _price) internal view returns (uint256) {
        // NOTE: We don't use SafeMath (or similar) in this function because
        //  all of our entry functions carefully cap the maximum values for
        //  currency (at 128-bits), and ownerCut <= 10000 (see the require()
        //  statement in the CSLClockSales constructor). The result of this
        //  function is always guaranteed to be <= _price.
        return _price.mul(ownerCut.div(10000));
    }
/**
 * @dev        Computes owner's cut of a sale.
 * @param      _price  The price
 */