contract VaultHandlerV5 is ReentrancyGuard {
    
    using SafeMath for uint256;
    using SafeMath for uint8;
    address payable private owner;
    string public metadataBaseUri;
    bool public initialized;
    address public nftAddress;
    address public paymentAddress;
    address public recipientAddress;
    address public couponAddress;
    uint256 public price;
    uint256 public offerPrice = 0;
    bool public payToAcceptOffer = false;
    bool public payToMakeOffer = false;
    bool public shouldBurn = false;
    
    struct PreMint {
        string payload;
        bytes32 preImage;
    }
    
    struct PreTransfer {
        string payload;
        bytes32 preImage;
        address _from;
    }
    
    struct Offer {
        uint tokenId;
        address _from;
    }

    
    // mapping(uint => PreMint) public tokenIdToPreMint;
    mapping(address => mapping(uint => PreMint)) preMints;
    mapping(address => mapping(uint => PreMint)) preMintsByIndex;
    mapping(address => uint) preMintCounts;
    
    mapping(uint => PreTransfer) preTransfers;
    mapping(uint => mapping(uint => PreTransfer)) preTransfersByIndex;
    mapping(uint => uint) preTransferCounts;
    
    mapping(uint => Offer[]) offers;
    mapping(uint => Offer[]) rejected;
    mapping(address => mapping(uint => Offer)) offered;
    
    mapping(address => bool) public witnesses;
    mapping(uint256 => bool) usedNonces;
    
    
    // event for EVM logging
    event OwnerSet(address indexed oldOwner, address indexed newOwner);
    
    // modifier to check if caller is owner
    modifier isOwner() {
        // If the first argument of 'require' evaluates to 'false', execution terminates and all
        // changes to the state and to Ether balances are reverted.
        // This used to consume all gas in old EVM versions, but not anymore.
        // It is often a good idea to use 'require' to check if functions are called correctly.
        // As a second argument, you can also provide an explanation about what went wrong.
        require(msg.sender == owner, "Caller is not owner");
        _;
    }
    
    /**
     * @dev Change owner
     * @param newOwner address of new owner
     */
    function transferOwnership(address payable newOwner) public isOwner {
        emit OwnerSet(owner, newOwner);
        owner = newOwner;
    }
    
    /**
     * @dev Return owner address 
     * @return address of owner
     */
    function getOwner() external view returns (address) {
        return owner;
    }
    
    constructor(address _nftAddress, address _paymentAddress, address _recipientAddress, uint256 _price) public {
        owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
        emit OwnerSet(address(0), owner);
        addWitness(owner);
        metadataBaseUri = "http://104.154.252.216/meta/";
        nftAddress = _nftAddress;
        paymentAddress = _paymentAddress;
        recipientAddress = _recipientAddress;
        initialized = true;
        uint decimals = BasicERC20(paymentAddress).decimals();
        price = _price * 10 ** decimals;
    }
    
    function claim(uint256 tokenId) public isOwner {
        IERC721 token = IERC721(nftAddress);
        token.burn(tokenId);
    }
    
    function buyWithPaymentOnly(address _to, uint256 _tokenId, string calldata image) public payable {
        IERC20Token paymentToken = IERC20Token(paymentAddress);
        IERC721 nftToken = IERC721(nftAddress);
        PreMint memory preMint = preMints[msg.sender][_tokenId];
        require(preMint.preImage == sha256(abi.encodePacked(image)), 'Payload does not match'); // Payload should match
        if (shouldBurn) {
            require(paymentToken.transferFrom(msg.sender, address(this), price), 'Transfer ERROR'); // Payment sent to recipient
            BasicERC20(paymentAddress).burn(price);
        } else {
            require(paymentToken.transferFrom(msg.sender, address(recipientAddress), price), 'Transfer ERROR'); // Payment sent to recipient
        }
        string memory _uri = concat(metadataBaseUri, uintToStr(_tokenId));
        nftToken.mint(_to, _tokenId, _uri, preMint.payload);
        delete preMintsByIndex[msg.sender][preMintCounts[msg.sender]];
        delete preMints[msg.sender][_tokenId];
        preMintCounts[msg.sender] = preMintCounts[msg.sender].sub(1);
    }
    
    function addPreMint(address _for, string calldata _payload, uint256 _tokenId, bytes32 preImage) public isOwner {
        try IERC721(nftAddress).tokenPayload(_tokenId) returns (string memory) {
            revert('NFT Exists with this ID');
        } catch {
            require(!_duplicatePremint(_for, _tokenId), 'Duplicate PreMint');
            preMintCounts[_for] = preMintCounts[_for].add(1);
            preMints[_for][_tokenId] = PreMint(_payload, preImage);
            preMintsByIndex[_for][preMintCounts[_for]] = preMints[_for][_tokenId];
        }
    }
    
    function _duplicatePremint(address _for, uint256 _tokenId) internal view returns (bool) {
        string memory data = preMints[_for][_tokenId].payload;
        bytes32 NULL = keccak256(bytes(''));
        return keccak256(bytes(data)) != NULL;
    }
    
    function deletePreMint(address _for, uint256 _tokenId) public isOwner {
        delete preMintsByIndex[_for][preMintCounts[_for]];
        preMintCounts[_for] = preMintCounts[_for].sub(1);
        delete preMints[_for][_tokenId];
    }
    
    function getPreMint(address _for, uint256 _tokenId) public view returns (PreMint memory) {
        return preMints[_for][_tokenId];
    }
    
    function checkPreMintImage(string memory image, bytes32 preImage) public pure returns (bytes32, bytes32, bool) {
        bytes32 calculated = sha256(abi.encodePacked(image));
        bytes32 preBytes = preImage;
        return (calculated, preBytes, calculated == preBytes);
    }
    
    function getPreMintCount(address _for) public view returns (uint length) {
        return preMintCounts[_for];
    }
    
    function getPreMintByIndex(address _for, uint index) public view returns (PreMint memory) {
        return preMintsByIndex[_for][index];
    }
    
    function toggleShouldBurn() public {
        shouldBurn = !shouldBurn;
    }
    
    /* Transfer with code */
    function addWitness(address _witness) public isOwner {
        witnesses[_witness] = true;
    }

    function removeWitness(address _witness) public isOwner {
        witnesses[_witness] = false;
    }
    
    function getAddressFromSignature(uint256 _tokenId, uint256 _nonce, bytes memory signature) public view returns (address) {
        require(!usedNonces[_nonce]);
        bytes32 hash = keccak256(abi.encodePacked(concat(uintToStr(_tokenId), uintToStr(_nonce))));
        address addressFromSig = recoverSigner(hash, signature);
        return addressFromSig;
    }
    
    function transferWithCode(uint256 _tokenId, string calldata code, address _to, uint256 _nonce,  bytes memory signature) public payable {
        require(witnesses[getAddressFromSignature(_tokenId, _nonce, signature)], 'Not Witnessed');
        IERC721 nftToken = IERC721(nftAddress);
        PreTransfer memory preTransfer = preTransfers[_tokenId];
        require(preTransfer.preImage == sha256(abi.encodePacked(code)), 'Code does not match'); // Payload should match
        nftToken.transferFrom(preTransfer._from, _to,  _tokenId);
        delete preTransfers[_tokenId];
        delete preTransfersByIndex[_tokenId][preTransferCounts[_tokenId]];
        preTransferCounts[_tokenId] = preTransferCounts[_tokenId].sub(1);
        usedNonces[_nonce] = true;
    }
    
    function addPreTransfer(uint256 _tokenId, bytes32 preImage) public {
        require(!_duplicatePretransfer(_tokenId), 'Duplicate PreTransfer');
        preTransferCounts[_tokenId] = preTransferCounts[_tokenId].add(1);
        preTransfers[_tokenId] = PreTransfer("payload", preImage, msg.sender);
        preTransfersByIndex[_tokenId][preTransferCounts[_tokenId]] = preTransfers[_tokenId];
    }
    
    function _duplicatePretransfer(uint256 _tokenId) internal view returns (bool) {
        string memory data = preTransfers[_tokenId].payload;
        bytes32 NULL = keccak256(bytes(''));
        return keccak256(bytes(data)) != NULL;
    }
    
    function deletePreTransfer(uint256 _tokenId) public {
        require(preTransfers[_tokenId]._from == msg.sender, 'PreTransfer does not belong to sender');
        delete preTransfersByIndex[_tokenId][preTransferCounts[_tokenId]];
        preTransferCounts[_tokenId] = preTransferCounts[_tokenId].sub(1);
        delete preTransfers[_tokenId];
    }
    
    function getPreTransfer(uint256 _tokenId) public view returns (PreTransfer memory) {
        return preTransfers[_tokenId];
    }
    
    function checkPreTransferImage(string memory image, bytes32 preImage) public pure returns (bytes32, bytes32, bool) {
        bytes32 calculated = sha256(abi.encodePacked(image));
        bytes32 preBytes = preImage;
        return (calculated, preBytes, calculated == preBytes);
    }
    
    function getPreTransferCount(uint256 _tokenId) public view returns (uint length) {
        return preTransferCounts[_tokenId];
    }
    
    function getPreTransferByIndex(uint256 _tokenId, uint index) public view returns (PreTransfer memory) {
        return preTransfersByIndex[_tokenId][index];
    }
    
    /* Swap */
    
    function acceptOffer(uint _tokenId, uint index) public {
        Offer memory _offer = offers[_tokenId][index];
        IERC721 nftToken = IERC721(nftAddress);
        IERC20Token couponToken = IERC20Token(couponAddress);
        require(nftToken.ownerOf(_tokenId) == msg.sender,'Sender is not owner of NFT');
        require(nftToken.ownerOf(_offer.tokenId) == _offer._from, 'NFT not owned by offerer');
        require(nftToken.getApproved(_offer.tokenId) == address(this), 'Handler unable to transfer offer NFT');
        require(nftToken.getApproved(_tokenId) == address(this), 'Handler unable to transfer NFT');
        if (offerPrice > 0 && payToAcceptOffer) {
            require(couponToken.allowance(msg.sender, address(this)) >= offerPrice, 'Handler unable take payment for offer');
            require(couponToken.balanceOf(msg.sender) >= offerPrice, 'Insufficient Balance for payment');
            require(couponToken.transferFrom(msg.sender, paymentAddress, offerPrice), 'Payment error');
        }
        nftToken.safeTransferFrom(_offer._from, msg.sender, _offer.tokenId);
        nftToken.safeTransferFrom(msg.sender, _offer._from, _tokenId);
        
        delete offers[_tokenId][index];
        delete offered[_offer._from][_tokenId];
    }
    
    function addOffer(uint256 _tokenId, uint256 _for) public {
        IERC721 nftToken = IERC721(nftAddress);
        IERC20Token couponToken = IERC20Token(couponAddress);
        require(nftToken.ownerOf(_tokenId) == msg.sender, 'Sender not owner of NFT');
        require(nftToken.getApproved(_tokenId) == address(this), 'Handler unable to transfer NFT');
        if (offerPrice > 0 && payToMakeOffer) {
            require(couponToken.allowance(msg.sender, address(this)) >= offerPrice, 'Handler unable take payment for offer');
            require(couponToken.balanceOf(msg.sender) >= offerPrice, 'Insufficient Balance for payment');
            require(couponToken.transferFrom(msg.sender, paymentAddress, offerPrice), 'Payment error');
        }
        offers[_for].push(Offer(_tokenId, msg.sender));
        offered[msg.sender][_tokenId] = Offer(_tokenId, msg.sender);
    }
    
    function rejectOffer(uint256 _tokenId, uint index) public {
        Offer memory _offer = offers[_tokenId][index];
        IERC721 nftToken = IERC721(nftAddress);
        require(nftToken.ownerOf(_tokenId) == msg.sender,'Sender is not owner of NFT');
        rejected[_tokenId].push(_offer);
        delete offers[_tokenId][index];
        delete offered[_offer._from][_tokenId];
    }
    
    function withdrawOffer(uint256 _tokenId, uint index) public {
        Offer memory _offer = offers[_tokenId][index];
        IERC721 nftToken = IERC721(nftAddress);
        require(nftToken.ownerOf(_offer.tokenId) == msg.sender,'Sender is not owner of offer NFT');
        delete offers[_tokenId][index];
        delete offered[_offer._from][_tokenId];
    }
    
    function togglePayToMakeOffer() public isOwner {
        payToMakeOffer = !payToMakeOffer;
    }
    function togglePayToAcceptOffer() public isOwner {
        payToAcceptOffer = !payToAcceptOffer;
    }
    
    function getOffer(uint256 _tokenId, uint index) public view returns (Offer memory) {
        return offers[_tokenId][index];
    }
    
    function getOfferCount(uint256 _tokenId) public view returns (uint) {
        return offers[_tokenId].length;
    }
    
    function changeMetadataBaseUri(string calldata _uri) public isOwner {
        metadataBaseUri = _uri;
    }
    
    function transferPaymentOwnership(address newOwner) external isOwner {
        Ownable paymentToken = Ownable(paymentAddress);
        paymentToken.transferOwnership(newOwner);
    }
    
    function transferNftOwnership(address newOwner) external isOwner {
        Ownable nftToken = Ownable(nftAddress);
        nftToken.transferOwnership(newOwner);
    }
    
    function mint( address _to, uint256 _tokenId, string calldata _uri, string calldata _payload) external isOwner {
        IERC721 nftToken = IERC721(nftAddress);
        nftToken.mint(_to, _tokenId, _uri, _payload);
    }
    
    function changeName(string calldata name, string calldata symbol) external isOwner {
        IERC721 nftToken = IERC721(nftAddress);
        nftToken.changeName(name, symbol);
    }
    
    function updateTokenUri(uint256 _tokenId,string memory _uri) external isOwner {
        IERC721 nftToken = IERC721(nftAddress);
        nftToken.updateTokenUri(_tokenId, _uri);
    }
    
    function getPaymentDecimals() public view returns (uint8){
        BasicERC20 token = BasicERC20(paymentAddress);
        return token.decimals();
    }
    
    function changePayment(address payment) public isOwner {
       paymentAddress = payment;
    }
    
    function changeCoupon(address coupon) public isOwner {
       couponAddress = coupon;
    }
    
    function changeRecipient(address _recipient) public isOwner {
       recipientAddress = _recipient;
    }
    
    function changeNft(address token) public isOwner {
        nftAddress = token;
    }
    
    function changePrice(uint256 _price) public isOwner {
        uint decimals = BasicERC20(paymentAddress).decimals();
        price = _price * 10 ** decimals;
    }
    
    function changeOfferPrice(uint256 _price) public isOwner {
        uint decimals = BasicERC20(couponAddress).decimals();
        offerPrice = _price * 10 ** decimals;
    }
    
    function concat(string memory a, string memory b) internal pure returns (string memory) {
        return string(abi.encodePacked(a, b));
    }
    
    /**
    * @dev Recover signer address from a message by using their signature
    * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
    * @param sig bytes signature, the signature is generated using web3.eth.sign(). Inclusive "0x..."
    */
    function recoverSigner(bytes32 hash, bytes memory sig) public pure returns (address) {
        require(sig.length == 65, "Require correct length");

        bytes32 r;
        bytes32 s;
        uint8 v;

        // Divide the signature in r, s and v variables
        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            v := byte(0, mload(add(sig, 96)))
        }

        // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
        if (v < 27) {
            v += 27;
        }

        require(v == 27 || v == 28, "Signature version not match");

        return recoverSigner2(hash, v, r, s);
    }

    function recoverSigner2(bytes32 h, uint8 v, bytes32 r, bytes32 s) public pure returns (address) {
        bytes memory prefix = "\x19Ethereum Signed Message:\n32";
        bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h));
        address addr = ecrecover(prefixedHash, v, r, s);

        return addr;
    }
    
    /// @notice converts number to string
    /// @dev source: https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol#L1045
    /// @param _i integer to convert
    /// @return _uintAsString
    function uintToStr(uint _i) internal pure returns (string memory _uintAsString) {
        uint number = _i;
        if (number == 0) {
            return "0";
        }
        uint j = number;
        uint len;
        while (j != 0) {
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len - 1;
        while (number != 0) {
            bstr[k--] = byte(uint8(48 + number % 10));
            number /= 10;
        }
        return string(bstr);
    }
    
    function stringToBytes32(string memory source) public pure returns (bytes32 result) {
        bytes memory tempEmptyStringTest = bytes(source);
        if (tempEmptyStringTest.length == 0) {
            return 0x0;
        }
    
        assembly {
            result := mload(add(source, 32))
        }
    }
    function bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) {

        // string memory str = string(_bytes32);
        // TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer"
        // thus we should fist convert bytes32 to bytes (to dynamically-sized byte array)
    
        bytes memory bytesArray = new bytes(32);
        for (uint256 i; i < 32; i++) {
            bytesArray[i] = _bytes32[i];
            }
        return string(bytesArray);
    }
}
function transferOwnership(address payable newOwner) public isOwner {
        emit OwnerSet(owner, newOwner);
        owner = newOwner;
    }
/**
 * @dev Change owner
 * @param newOwner address of new owner
 */