// Contract: MartianMarketWL
// Target function: function purchaseWLVendingItem(address contract_, uint256 index_) external
 start_, generally you can use 0, and for end_, inquire from function
        getWLVendingItemsLength(address contract_)

    For interaction of users:

        purchaseWLVendingItem(address contract_, uint256 index_) can be used
        and automatically populated to the correct buttons for each WLVendingItem
        for that, an ethers.js call is invoked for the user to call the function
        which will transfer their ERC20 token and add them to the purchasers list

    For administration:

        setTreasuryAddress(address contract_, address treasury_) can only be set
        by the contract owner. For this, they are able to set where the ERC20 tokens
        from the whitelist marketplace sales go to. By default, this is 0x...dead
        effectively burning the tokens

        addWLVendingItem(address contract_, string calldata title_, 
        string calldata imageUri_, string calldata projectUri_,
        string calldata description_, uint32 amountAvailable_, uint32 deadline_,
        uint256 price_) is used to create a new WLVendingItem for your contract
        with the details as the input arguments stated.

        modifyWLVendingItem(address contract_, uint256 index_, 
        WLVendingItem memory WLVendingItem_) lets you modify a WLVendingItem.
        You have to pass in a tuple instead. Only use when necessary. Not
        recommended to use.

        deleteMostRecentWLVendingItem(address contract_) we use a .pop() for this so
        it can only delete the most recent item. For some mistakes that you made and
        want to erase them.

        manageController(address contract_, address operator_, bool bool_) is a special
        governance function which allows you to add controllers to the contract
        to do actions on your behalf. 
*/

/*
    Patch Notes: 3.1.2

    - verify project ownership to purchase tokens (ownershipController) [/]

*/

abstract contract Ownable {
    address public owner; 
    constructor() { owner = msg.sender; }
    modifier onlyOwner { require(owner == msg.sender, "Not Owner!"); _; }
    function transferOwnership(address new_) external onlyOwner { owner = new_; }
}

interface IERC20 {
    function owner() external view returns (address);
    function balanceOf(address address_) external view returns (uint256);
    function transfer(address to_, uint256 amount_) external returns (bool);
    function transferFrom(address from_, address to_, uint256 amount_) external;
}

interface IOwnable {
    function owner() external view returns (address);
}

interface IPriceController {
    function getPriceOfItem(address contract_, uint256 index_) external view
    returns (uint256);
}

interface ITokenController {
    function getTokenNameOfItem(address contract_, uint256 index_) external view
    returns (string memory);
    function getTokenImageOfItem(address contract_, uint256 index_) external view
    returns (string memory);
    function getTokenOfItem(address contract_, uint256 index_) external view
    returns (address);
}

// Patch 3.2 - ownershipController for Token Ownership Access
interface IOwnershipController {
    function hasOwnershipOfToken(address contract_, address owner_) external view
    returns (bool);
}

// Patch 3.2+ - mockTokens Future Support
interface IMockTokens {
    function transferMockTokens(address contract_, address from_, address to_,
    uint256 amount_) external;
}

contract MartianMarketWL is Ownable {

    // Events
    event TreasuryManaged(address indexed contract_, address indexed operator_,
        address treasury_);
    event TokenManaged(address indexed contract_, address indexed operator_,
        address token_);

    event OperatorManaged(address indexed contract_, address indexed operator_, 
        bool bool_);
    event MarketAdminManaged(address indexed contract_, address indexed operator_,
        address admin_, bool bool_);
    event RequiresTokenManaged(address indexed contract_, address indexed operator_,    
        bool bool_);

    event GovernorUnstuckOwner(address indexed contract_, address indexed operator_,
        address unstuckOwner_);

    event WLVendingItemAdded(address indexed contract_, address indexed operator_,
        WLVendingItem item_);
    event WLVendingItemModified(address indexed contract_, address indexed operator_, 
        WLVendingItem before_, WLVendingItem after_);
    event WLVendingItemRemoved(address indexed contract_, address indexed operator_,
        WLVendingItem item_);
    event WLVendingItemPurchased(address indexed contract_, address indexed purchaser_, 
        uint256 index_, WLVendingObject object_);
    event WLVendingItemGifted(address indexed contract_, address indexed gifted_,
        uint256 index_, WLVendingObject object_);

    event ContractRegistered(address indexed contract_, address registerer_,
        uint256 registrationPrice_);
    event ContractAdministered(address indexed contract_, address registerer_,
        bool bool_);

    event ProjectInfoPushed(address indexed contract_, address registerer_,
        string projectName_, string tokenImage_);

    // Governance
    IERC20 public MES = 
        IERC20(0x3C2Eb40D25a4b2B5A068a959a40d57D63Dc98B95);
    function O_setMES(address address_) external onlyOwner {
        MES = IERC20(address_);
    } // good

    ITokenController public TokenController = 
        ITokenController(0x3C2Eb40D25a4b2B5A068a959a40d57D63Dc98B95);
    function O_setTokenController(address address_) external onlyOwner {
        TokenController = ITokenController(address_);
    } // good

    IPriceController public PriceController = 
        IPriceController(0x3C2Eb40D25a4b2B5A068a959a40d57D63Dc98B95);
    function O_setPriceController(address address_) external onlyOwner {
        PriceController = IPriceController(address_);
    } // good

    IOwnershipController public OwnershipController = 
        IOwnershipController(0x7B41E6Cb678F8e12134a645fb341F928DA91A17b);
    function O_setOwnershipController(address address_) external onlyOwner {
        OwnershipController = IOwnershipController(address_);
    }

    // Setting the Governor - good
    address public superGovernorAddress;
    address public governorAddress;
    address public registrationCollector;
    
    constructor() {
        superGovernorAddress = msg.sender;
        governorAddress = msg.sender;
        registrationCollector = address(this);
    } 

    // Ownable Governance Setup - good
    function O_setSuperGovernorAddress(address superGovernor_) external onlyOwner {
        // If superGovernor has been renounced, it is never enabled again.
        require(superGovernorAddress != address(0),
            "Super Governor Access has been renounced");

        superGovernorAddress = superGovernor_;
    } 
    modifier onlySuperGovernor {
        require(msg.sender == superGovernorAddress,
            "You are not the contract super governor!");
        _;
    } 
    function O_setGovernorAddress(address governor_) external onlyOwner {
        governorAddress = governor_;
    }
    modifier onlyGovernor {
        require(msg.sender == governorAddress,
            "You are not the contract governor!");
        _;
    }

    // Project Control (Super Governor) - good
    mapping(address => address) contractToUnstuckOwner;

    function SG_SetContractToVending(address contract_, bool bool_) external
    onlySuperGovernor {
        require(contractToEnabled[contract_] != bool_,
            "Contract Already Set as Boolean!");

        // Set contract as enabled
        contractToEnabled[contract_] = bool_;
        
        // Enum Tracking on bool_ statement
        bool_ ? _addContractToEnum(contract_) : _removeContractFromEnum(contract_);
        
        emit ContractAdministered(contract_, msg.sender, bool_);
    }
    function SG_SetContractToProjectInfo(address contract_, string calldata 
    projectName_, string calldata tokenName_, string calldata tokenImage_) 
    external onlySuperGovernor {
        
        contractToProjectInfo[contract_] = ProjectInfo(
            projectName_, 
            tokenName_,
            tokenImage_
        );
        
        emit ProjectInfoPushed(contract_, msg.sender, projectName_, tokenImage_);
    }
    function SG_SetStuckOwner(address contract_, address unstuckOwner_) 
    external onlySuperGovernor {

        // Onboarding for ERC20 of non-initialized contracts
        // In case of renounced or unretrievable owners

        // I the contract was not enabled by the super governor, but 
        // through user registration by paying $MES, this function 
        // is forever disabled for them.
        require(!contractToMESRegistry[contract_],
            "Ownership has been proven through registration.");

        // For maximum trustlessness, this can only be used if there has never been
        // an item created in their store. Once they create an item, this effectively
        // proves ownership is intact and disables this ability forever.
        require(contractToWLVendingItems[contract_].length == 0,
            "Ownership has been proven.");
            
        contractToUnstuckOwner[contract_] = unstuckOwner_;

        // 2022-04-07 ~0xInuarashi removed this because it stucks on invalid owner()
        // emit GovernorUnstuckOwner(contract_, msg.sender, 
            // IERC20(contract_).owner(), unstuckOwner_);

        // 2022-04-07 ~0xInuarashi added this as no interface event
        emit GovernorUnstuckOwner(contract_, msg.sender, unstuckOwner_);
    }
    
    // Registry Control (Governor) - ok
    uint256 public registrationPrice = 20000 ether; // 20000 $MES
    function G_setRegistrationPrice(uint256 price_) external onlyGovernor {
        registrationPrice = price_;
    }
    function G_setRegistrationCollector(address collector_) external onlyGovernor {
        registrationCollector = collector_;
    }
    function G_withdrawMESfromContract(address receiver_) external onlyGovernor {
        MES.transfer(receiver_, MES.balanceOf(address(this)));
    }

    // Registry Logic
    // Database Entry for Enabled Addresses + Enumeration System // - good
    mapping(address => bool) public contractToEnabled;

    // Enumeration Tools 
    address[] public enabledContracts;
    mapping(address => uint256) public enabledContractsIndex;

    function getAllEnabledContracts() external view returns (address[] memory) {
        return enabledContracts;
    }
    function _addContractToEnum(address contract_) internal {
        enabledContractsIndex[contract_] = enabledContracts.length;
        enabledContracts.push(contract_);
    }
    function _removeContractFromEnum(address contract_) internal {
        uint256 _lastIndex = enabledContracts.length - 1;
        uint256 _currentIndex = enabledContractsIndex[contract_];

        // If the contract is not the last contract in the array
        if (_currentIndex != _lastIndex) {
            // Replace the to-be-deleted address with the last address
            address _lastAddress = enabledContracts[_lastIndex];
            enabledContracts[_currentIndex] = _lastAddress;
        }

        // Remove the last item
        enabledContracts.pop();
        // Delete the index
        delete enabledContractsIndex[contract_];
    }

    // Registry (Contract Owner) - good
    mapping(address => bool) public contractToMESRegistry;

    function registerContractToVending(address contract_) external {
        require(msg.sender == IOwnable(contract_).owner(),
            "You are not the Contract Owner!");
        require(!contractToEnabled[contract_],
            "Your contract has already been registered!");
        require(MES.balanceOf(msg.sender) >= registrationPrice,
            "You don't have enough $MES!");
        
        MES.transferFrom(msg.sender, registrationCollector, registrationPrice);
        
        contractToEnabled[contract_] = true;
        contractToMESRegistry[contract_] = true;

        _addContractToEnum(contract_);
        
        emit ContractRegistered(contract_, msg.sender, registrationPrice);
    }

    // Contract Owner Governance Control - ok
    function contractOwner(address contract_) public view returns (address) { 
        // If there is a contractToUnstuckOwner, return that. otherwise, return Ownable
        return contractToUnstuckOwner[contract_] != address(0) ?
            contractToUnstuckOwner[contract_] : IOwnable(contract_).owner();
    }
    modifier onlyContractOwnerEnabled (address contract_) {
        require(msg.sender == contractOwner(contract_),
            "You are not the Contract Owner!");
        require(contractToEnabled[contract_],
            "Please register your Contract first!");
        _;
    }
    modifier onlyAuthorized (address contract_, address operator_) {
        require(contractToControllersApproved[contract_][operator_]
            || msg.sender == contractOwner(contract_),
            "You are not Authorized for this Contract!");
        require(contractToEnabled[contract_],
            "Contract is not enabled!");
        _;
    }

    // External Interface Access - ok
    function isContractOwner(address contract_, address sender_) public 
    view returns (bool) {
        return contractOwner(contract_) == sender_;    
    }
    function isAuthorized(address contract_, address operator_) public
    view returns (bool) {
        if (contractToControllersApproved[contract_][operator_]) return true;
        else return contractOwner(contract_) == operator_;
    }

    // Project Control (Contract Owner) - ok
    struct ProjectInfo {
        string projectName;
        string tokenName;
        string tokenImageUri;
    }
    
    mapping(address => ProjectInfo) public contractToProjectInfo;
    
    function registerProjectInfo(address contract_, string calldata projectName_,
    string calldata tokenName_, string calldata tokenImage_) 
    external onlyContractOwnerEnabled(contract_) {
    
        contractToProjectInfo[contract_] = ProjectInfo(
            projectName_, 
            tokenName_,
            tokenImage_
        );
    
        emit ProjectInfoPushed(contract_, msg.sender, projectName_, tokenImage_);
    }

    mapping(address => mapping(address => bool)) public contractToControllersApproved;
    
    function manageController(address contract_, address operator_, bool bool_) 
    external onlyContractOwnerEnabled(contract_) {

        contractToControllersApproved[contract_][operator_] = bool_;
        
        emit OperatorManaged(contract_, operator_, bool_);
    }

    address public burnAddress = 0x000000000000000000000000000000000000dEaD;
    mapping(address => address) public contractToTreasuryAddress;
    
    function getTreasury(address contract_) public view returns (address) {
        // if contractToTreasuryAddress is set, use that, otherwise, burnAddress
        return contractToTreasuryAddress[contract_] != address(0) ? 
            contractToTreasuryAddress[contract_] : burnAddress; 
    }
    function setTreasuryAddress(address contract_, address treasury_) external 
    onlyContractOwnerEnabled(contract_) {

        contractToTreasuryAddress[contract_] = treasury_;

        emit TreasuryManaged(contract_, msg.sender, treasury_);
    }

    // Patch 3.1.2 Token Ownership Control & Access
    mapping(address => bool) public requiresTokenOwnership;

    function setRequiresTokenOwnership(address contract_, bool bool_) external
    onlyContractOwnerEnabled(contract_) {

        requiresTokenOwnership[contract_] = bool_;

        emit RequiresTokenManaged(contract_, msg.sender, bool_);
    }


    // Whitelist Marketplace - ok
    struct WLVendingItem {
        string title; // for metadata uri, set title to metadata uri instead
        string imageUri;
        string projectUri;
        string description;

        uint32 amountAvailable;
        uint32 amountPurchased;

        uint32 startTime;
        uint32 endTime;
        
        uint256 price;
    }

    // Database of Vending Items for each ERC20
    mapping(address => WLVendingItem[]) public contractToWLVendingItems;
    
    // Database of Vending Items Purchasers for each ERC20
    mapping(address => mapping(uint256 => address[])) public contractToWLPurchasers;
    mapping(address => mapping(uint256 => mapping(address => bool))) public 
        contractToWLPurchased;

    function addWLVendingItem(address contract_, WLVendingItem memory WLVendingItem_)
    external onlyAuthorized(contract_, msg.sender) {
        require(bytes(WLVendingItem_.title).length > 0,
            "You must specify a Title!");
        require(uint256(WLVendingItem_.endTime) > block.timestamp,
            "Already expired timestamp!");
        require(WLVendingItem_.endTime > WLVendingItem_.startTime,
            "endTime > startTime!");
        
        // Make sure that amountPurchased on adding is always 0
        WLVendingItem_.amountPurchased = 0;

        // Push the item to the database array
        contractToWLVendingItems[contract_].push(WLVendingItem_);
        
        emit WLVendingItemAdded(contract_, msg.sender, WLVendingItem_);
    }

    function modifyWLVendingItem(address contract_, uint256 index_,
    WLVendingItem memory WLVendingItem_) external 
    onlyAuthorized(contract_, msg.sender) {
        WLVendingItem memory _item = contractToWLVendingItems[contract_][index_];

        require(bytes(_item.title).length > 0,
            "This WLVendingItem does not exist!");
        require(bytes(WLVendingItem_.title).length > 0,
            "Title must not be empty!");
        
        require(WLVendingItem_.amountAvailable >= _item.amountPurchased,
            "Amount Available must be >= Amount Purchased!");

        // ~0xInuarashi @ 2022-04-29 - always set new amountPurchased to old
        WLVendingItem_.amountPurchased = _item.amountPurchased;
        
        contractToWLVendingItems[contract_][index_] = WLVendingItem_;
        
        emit WLVendingItemModified(contract_, msg.sender, _item, WLVendingItem_);
    }

    function deleteMostRecentWLVendingItem(address contract_) external
    onlyAuthorized(contract_, msg.sender) {
        uint256 _lastIndex = contractToWLVendingItems[contract_].length - 1;

        WLVendingItem memory _item = contractToWLVendingItems[contract_][_lastIndex];

        require(_item.amountPurchased == 0,
            "Cannot delete item with already bought goods!");
        
        contractToWLVendingItems[contract_].pop();
        emit WLVendingItemRemoved(contract_, msg.sender, _item);
    }