// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: contracts/Crowdfunding.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract Crowdfunding is ReentrancyGuard {
   
    struct Campaign {
        address owner;
        string title;
        string url;
        string description;
        uint256 target;
        uint256 deadline;
        uint256 amountCollected;
        string image;
        address[] donators;
        uint256[] donations;
        address invited;
        bool exists;
    }
    
    IERC20 private _token;
    address private _owner;
    address public _crowdfunding;

    address payable public wallet;

    mapping(uint256 => Campaign) public campaigns;
    mapping (uint256 => bool) public votingsCampaigns;

    uint256 public numberOfCampaigns = 0;
    uint256 public tokenAmount;

    modifier onlyOwner() {
        require(msg.sender == _owner, "owner only");
        _;
    }

    event TokenDonate(
        address indexed purchaser,
        address indexed beneficiary,
        uint256 amount
    );

    constructor(IERC20 token, uint256 _tokenAmount, address payable _wallet) ReentrancyGuard() {
        require(_wallet != address(0));
        _token = token;
        tokenAmount = _tokenAmount * 10 ** 18;
        _owner = msg.sender;
        wallet = _wallet;
    }

    function createCampaign(string memory _title, string memory _url, string memory _description, uint256 _target, uint256 _deadline, string memory _image, address _invited) nonReentrant public returns (uint256) {
        uint _titleLength = bytes(_title).length;
        uint _descriptionLength = bytes(_description).length;
        require(_target >= 100 * 10 ** 18, "Mininum voice 100 GRAv");
        require(_target <= 500 * 10 ** 18, "Maximum voice 500 GRAv");
        require(_deadline > block.timestamp, 'Check you deadline');
        require(_getBalance(msg.sender) > 1000 * 10 ** 18, "You must need to buy GRAV");
        require(_titleLength < 50, "Title is so long");
        require(_descriptionLength < 200, "Description is so long");
        Campaign storage campaign = campaigns[numberOfCampaigns];       

        campaign.owner = msg.sender;
        campaign.title = _title;
        campaign.url = _url;
        campaign.description = _description;
        campaign.target = _target;
        campaign.deadline = _deadline;
        campaign.amountCollected = 0;
        campaign.image = _image;
        campaign.invited = _invited;
        campaign.exists = true;

        numberOfCampaigns++;

        return numberOfCampaigns - 1;
    }

    function donateToCampaign(uint256 _id) nonReentrant public payable {
        uint256 bal = _getBalance(msg.sender);
        
        Campaign storage campaign = campaigns[_id];
        require(_getBalance(msg.sender) > 1000 * 10 ** 18, "You must need to buy GRAV");
        require(campaign.exists == true, 'Project missing');
        require(campaign.deadline > block.timestamp, 'Voting over you can create a new');
        
        _preValidatePurchase(msg.sender, 0, bal, campaign.owner, _id);
        _processPurchase(campaign.owner, tokenAmount);

        emit TokenDonate(
            msg.sender,
            campaign.owner,
            tokenAmount
        );       
        
        campaign.donators.push(msg.sender);
        campaign.donations.push(tokenAmount);
        campaign.amountCollected = campaign.amountCollected + tokenAmount;
        
    }

    function getDonators(uint256 _id) view public returns(address[] memory, uint256[] memory) {
        Campaign storage campaign = campaigns[_id];
        require(campaign.exists == true, 'Project missing');
        require(_getBalance(msg.sender) > 1000 * 10 ** 18, "You must need to buy GRAV");
        return (campaigns[_id].donators, campaigns[_id].donations);
    }

    function getCampaigns() public view returns (Campaign[] memory) {
        Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);

        for (uint i = 0; i < numberOfCampaigns; i++) {
            Campaign storage item = campaigns[i];
            allCampaigns[i] = item;
        }
        return allCampaigns;
    }

    function getCampaign(uint256 _id) public view returns (Campaign memory) {
        require(_getBalance(msg.sender) > 1000 * 10 ** 18, "Insufficient GRAV");
        Campaign storage campaign = campaigns[_id];
        require(campaign.exists == true, 'Project missing');

        return campaign;
    }

    function _getBalance(address _addr) internal view returns (uint256) {
        return _token.balanceOf(_addr);
    }

    function _deliverTokens(
        address _to,
        uint256 _tokenAmount
    )
        internal
    {
        _token.transfer( _to, _tokenAmount);
    }

    function _preValidatePurchase(
        address _beneficiary,
        uint256 _weiAmount,
        uint256 _bal,
        address _campaingOwner,
        uint256 _id
    )
        internal view
    {
        require(_beneficiary != address(0));
        require(_weiAmount == 0);
        require(_bal > 1000 * 10 ** 18, "Insufficient GRAV");
        require(_campaingOwner != msg.sender, "Owner can`t voting");
        require(votingsCampaigns[_id], "Please provide a project number in support");
    }

    function _processPurchase(
        address _to,
        uint256 _tokenAmount
    )
        internal
    {
        _deliverTokens( _to, _tokenAmount);
    }

    function _getTokenAmount()
        public view returns (uint256)
    {
        return tokenAmount;
    }

    function setVoting(uint256 _id, uint256 _amount)
       nonReentrant public payable
    {
        uint256 bal = _getBalance(msg.sender);
        
        Campaign storage campaign = campaigns[_id];
        require(campaign.exists == true, 'Project missing');
        require(campaign.deadline > block.timestamp, "Voting over you can create a new");
        require(msg.sender != address(0));
        require(msg.sender == campaign.owner, "Publication owner only");
        require(bal > 1000 * 10 ** 18, "Insufficient GRAV");
        require(_amount >= 100 * 10 ** 18, "Minimum voting");
        require(_amount <= 500 * 10 ** 18, "Maximum voting");
        _processPurchase(_crowdfunding, _amount);

        emit TokenDonate(
            msg.sender,
            _crowdfunding,
            _amount
        );    
        votingsCampaigns[_id] = true;
    }

    function getVoting(uint256 _id) external view returns(bool) {
        return votingsCampaigns[_id];
    }

    function setCrowdfundingAddress(address _crowdfund) external onlyOwner {
        _crowdfunding = _crowdfund;
    }

}