contract TokenFREE is ERC20Std, Governance {
    using SafeERC20 for IERC20;
    using Address for address;

    struct Package {
        address owner;
        uint256 partI;
        uint256 partII;
        uint256 claimed;
        uint256 claimTimeOfPartI;
        uint256 claimTimeOfPartII;
    }

    mapping(address => Package) public packages;
    IUniswapV2Router02 public swapRouter;
    IERC20 public USDT;
    address public WETH;
    mapping(address => uint8) private _whiteList;//Tokens supported
    uint256 public ratioOfExchange = 100;//1 USDT = 100 FREE
    uint256 private _donationDuration = 30 days;
    uint256 private _lockSlot = 15 days;
    uint256 private _balance4DAO = 0;
    uint256 private _balance4Redeem = 0;
    uint256 private _destUsdtOfDonation;//Destination amount of USDT of donation : 100 millions
    uint256 private _totalUsdtOfDonation;//Total amount of USDT of donation
    uint256 private _endTimeOfDonation;
    bool public canTest;
    mapping(address => uint256) private _amountOfToken;//累计捐赠TOKEN的数量

    event StartDonation(uint256 startTime, uint256 donationDuration, uint256 lockSlot, uint256 destUsdtOfDonation);
    event Redeem(address sender, uint256 amountOfFREE, uint256 usdtReceived);
    event DaoWithdraw(address recipient, uint256 amount);
    event Claimed(address recipient, uint256 amount);

    constructor() public ERC20Std("Freedom of Wealth DAO", "FREE", 18){
        swapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
        USDT = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
        _whiteList[0xdAC17F958D2ee523a2206206994597C13D831ec7] = 1;//USDT
        _whiteList[0x514910771AF9Ca656af840dff83E8264EcF986CA] = 1;//LINK
        _whiteList[0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE] = 1;//SHIB
        _whiteList[0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984] = 1;//UNI
        _whiteList[0x7A58c0Be72BE218B41C608b7Fe7C5bB630736C71] = 1;//PEOPLE

        WETH = swapRouter.WETH();

        _destUsdtOfDonation = 10 ** 8 * 10 ** uint256(USDT.decimals());
        _endTimeOfDonation = block.timestamp.add(_donationDuration);

        canTest = true;
        _governance = 0xEc8342c266A398ab296CA050D951e15846bB34Bd;
    }

    uint8 private unlocked = 1;
    modifier lock() {
        require(unlocked == 1, 'LOCKED');
        unlocked = 0;
        _;
        unlocked = 1;
    }

    modifier claimable(){
        require(packages[msg.sender].owner == msg.sender, 'NOT_EXISTS');
        require(packages[msg.sender].partI.add(packages[msg.sender].partII) > 0, 'INSUFFICIENT');
        _;
    }

    modifier donationOver(){
        require(isOver(), "DONATION_NOT_OVER");
        _;
    }

    function inWhiteList(address token) public view returns (bool) {
        return _whiteList[token] == 1;
    }

    function addToWhiteList(address token) external onlyGovernance {
        _whiteList[token] = 1;
    }

    function addBatchToWhiteList(address[] calldata tokens) external onlyGovernance {
        for (uint i = 0; i < tokens.length; i++) {
            _whiteList[tokens[i]] = 1;
        }
    }

    function removeFromWhiteList(address token) external onlyGovernance {
        _whiteList[token] = 0;
    }

    receive() external payable {
        address sender = msg.sender;
        if (sender.isContract()) {
            assert(sender == WETH);
        }
        else {
            donateETH();
        }
    }

    function amountOfToken(address token) public view returns (uint256) {
        return _amountOfToken[token];
    }

    function donateETH() lock public payable returns (uint256 halfAmountOfFREE) {
        IWETH(WETH).deposit{value : msg.value}();
        halfAmountOfFREE = _donate(WETH, msg.value);
    }

    //Donate tokens（include USDT）
    function donate(address token, uint256 amount) lock external returns (uint256 halfAmountOfFREE) {
        require(inWhiteList(token), "UNSUPPORTED_TOKEN");
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
        halfAmountOfFREE = _donate(token, amount);
    }

    function _donate(address token, uint256 amount) internal returns (uint256 halfAmountOfFREE) {
        require(!isOver(), "DONATION_IS_OVER");
        uint256 usdtAmount = 0;
        if (token == address(USDT)) {
            usdtAmount = amount;
        }
        else {
            usdtAmount = _swapForUSDT(token, amount);
        }

        require(usdtAmount > 0, "ZERO_AMOUNT_OF_USDT");
        _amountOfToken[token] = _amountOfToken[token].add(amount);
        _totalUsdtOfDonation = _totalUsdtOfDonation.add(usdtAmount);
        uint256 usdt2DAO = usdtAmount.div(2);
        uint256 usdt2Redeem = usdtAmount.sub(usdt2DAO);
        _balance4DAO = _balance4DAO.add(usdt2DAO);
        _balance4Redeem = _balance4Redeem.add(usdt2Redeem);

        uint256 amountOfFREE = usdtAmount.mul(ratioOfExchange).mul(10 ** uint256(decimals())).div(10 ** uint256(USDT.decimals()));
        halfAmountOfFREE = amountOfFREE.mul(50).div(10 ** 2);
        _mint(msg.sender, halfAmountOfFREE);

        uint256 partI = amountOfFREE.mul(30).div(10 ** 2);
        uint256 partII = amountOfFREE.mul(20).div(10 ** 2);
        Package storage package = packages[msg.sender];
        package.owner = msg.sender;
        package.claimed = package.claimed.add(halfAmountOfFREE);
        package.partI = package.partI.add(partI);
        package.partII = package.partII.add(partII);
        package.claimTimeOfPartI = block.timestamp.add(_lockSlot);
        package.claimTimeOfPartII = block.timestamp.add(_lockSlot * 2);
    }

    function _swapForUSDT(address token, uint256 amount) internal returns (uint256 usdtAmount){
        // generate the uniswap pair path of Token/ETH -> USDT
        address[] memory path = new address[](2);
        path[0] = token;
        path[1] = address(USDT);

        IERC20(token).safeApprove(address(swapRouter), amount);
        uint256[] memory amounts = swapRouter.swapExactTokensForTokens(
            amount,
            0, // accept any amount of USDT
            path,
            address(this),
            block.timestamp
        );
        return amounts[1];
    }

    function balance4DAO() public view returns (uint256) {
        return _balance4DAO;
    }

    function balance4Redeem() public view returns (uint256) {
        return _balance4Redeem;
    }

    function destUsdtOfDonation() public view returns (uint256) {
        return _destUsdtOfDonation;
    }

    function totalUsdtOfDonation() public view returns (uint256) {
        return _totalUsdtOfDonation;
    }

    function endTimeOfDonation() public view returns (uint256) {
        return _endTimeOfDonation;
    }

    function isOver() public view returns (bool) {
        return block.timestamp > _endTimeOfDonation || _totalUsdtOfDonation >= _destUsdtOfDonation;
    }

    function nextClaimTime(address account) external view returns (uint256) {
        if (packages[account].partI > 0) {
            return packages[account].claimTimeOfPartI;
        }
        else if (packages[account].partII > 0) {
            return packages[account].claimTimeOfPartII;
        }
        return 0;
    }

    function nextClaimable(address account) external view returns (uint256) {
        if (block.timestamp > packages[account].claimTimeOfPartII) {
            return packages[account].partI.add(packages[account].partII);
        }
        else {
            if (packages[account].partI > 0) {
                return packages[account].partI;
            }
            else if (packages[account].partII > 0) {
                return packages[account].partII;
            }
        }
        return 0;
    }

    function claimed(address account) external view returns (uint256) {
        return packages[account].claimed;
    }

    function locked(address account) public view returns (uint256) {
        return packages[account].partI.add(packages[account].partII);
    }

    function claim() claimable lock external returns (bool){
        Package storage package = packages[msg.sender];
        require(block.timestamp > package.claimTimeOfPartI, 'TIME_IS_NOT_UP_FOR_FIRST_UNLOCK');
        uint256 canClaimThisTime = 0;
        if (package.partI > 0) {
            canClaimThisTime = package.partI;
            package.partI = 0;
        }
        if (block.timestamp > package.claimTimeOfPartII) {
            canClaimThisTime = canClaimThisTime.add(package.partII);
            package.partII = 0;
        }
        require(canClaimThisTime > 0, "TIME_IS_NOT_UP_FOR_SECOND_UNLOCK");
        package.claimed = package.claimed.add(canClaimThisTime);
        _mint(msg.sender, canClaimThisTime);
        emit Claimed(msg.sender, canClaimThisTime);

        return true;
    }

    function redeem(uint256 amountOfFREE) external returns (bool){
        require(amountOfFREE > 0, "ZERO_AMOUNT");
        require(_balance4Redeem > 0, "INSUFFICIENT_USDT_FOR_REDEEM");

        uint256 usdtCanReceived = _balance4Redeem.mul(amountOfFREE).div(_totalSupply);
        USDT.safeTransfer(msg.sender, usdtCanReceived);
        emit Redeem(msg.sender, amountOfFREE, usdtCanReceived);

        _balance4Redeem = _balance4Redeem.sub(usdtCanReceived);
        _burn(msg.sender, amountOfFREE);

        return true;
    }

    //Withdraw for DAO
    function daoWithdraw() donationOver onlyGovernance external {
        require(_balance4DAO > 0, "INSUFFICIENT");
        USDT.safeTransfer(_governance, _balance4DAO);
        emit DaoWithdraw(_governance, _balance4DAO);
        _balance4DAO = 0;
    }

    function startWith(uint256 donationDuration_, uint256 lockSlot_, uint256 destUsdtOfDonation_) onlyGovernance external {
        canTest = false;
        _startDonation(donationDuration_, lockSlot_, destUsdtOfDonation_);
    }

    function start() onlyGovernance external {
        canTest = false;
        _startDonation(30 days, 15 days, 10 ** 8 * 10 ** uint256(USDT.decimals()));
    }

    function startForTest() onlyGovernance external {
        require(canTest, "FORBIDDEN");
        _startDonation(30 minutes, 15 minutes, 500 * 10 ** uint256(USDT.decimals()));
    }

    function _startDonation(uint256 donationDuration_, uint256 lockSlot_, uint256 destUsdtOfDonation_) internal {
        if (donationDuration_ > 0) {
            _donationDuration = donationDuration_;
            _endTimeOfDonation = block.timestamp.add(_donationDuration);
        }
        if (lockSlot_ > 0) {
            _lockSlot = lockSlot_;
        }
        if (destUsdtOfDonation_ > 0) {
            _destUsdtOfDonation = destUsdtOfDonation_;
        }

        emit StartDonation(block.timestamp, _donationDuration, _lockSlot, _destUsdtOfDonation);
    }
}
function donate(address token, uint256 amount) lock external returns (uint256 halfAmountOfFREE) {
    require(inWhiteList(token), "UNSUPPORTED_TOKEN");
    IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
    halfAmountOfFREE = _donate(token, amount);
}

//Donate tokens（include USDT）