contract SeedPreSale is Ownable {
    uint public minPurchaseNum = 5*(10**17);
    uint public maxPurchaseNum = 50*(10**18);
    uint public preSaleLimit = 5000000*(10**18);
    bool public preSaleOpened = true;
    mapping (address => uint) public userPurchaseNumMap;
    ERC20 public seedContract;

    function SeedPreSale() public {
    }

    function setSeedContract(address seed) public onlyOwner {
        require(seedContract == ERC20(0));
        seedContract = ERC20(seed);
    }

    function setPreSaleOpened(bool opened) onlyOwner public {
        preSaleOpened = opened;
    }

    function getPurchaseETHNum() public view returns(uint) {
        return userPurchaseNumMap[msg.sender];
    }

    event Purchase(address user, uint num, uint money);

    /**
        预售购买接口
     */
    function () public payable {
        require(preSaleOpened);
        require(preSaleLimit > 0);
        require(seedContract != ERC20(0));
        require(msg.sender != owner);
        require(msg.value >= minPurchaseNum);
        require(userPurchaseNumMap[msg.sender] < maxPurchaseNum);

        uint allowed = seedContract.allowance(owner, this);
        require(allowed > 0);

        uint remaining = 0;
        uint purchaseMoney = msg.value;
        if (msg.value + userPurchaseNumMap[msg.sender] > maxPurchaseNum) {
            remaining = msg.value + userPurchaseNumMap[msg.sender] - maxPurchaseNum;
            purchaseMoney = maxPurchaseNum - userPurchaseNumMap[msg.sender];
        }

        remaining += purchaseMoney%2500;
        purchaseMoney -= purchaseMoney%2500;

        uint num = purchaseMoney/2500*(10**6);
        if (num > preSaleLimit || num > allowed) {
            if (preSaleLimit > allowed) {
                num = allowed;
            } else {
                num = preSaleLimit;
            }
            num -= num%(10**6);
            require(num > 0);
            remaining += purchaseMoney - num/(10**6)*2500;
            purchaseMoney = num/(10**6)*2500;
        }

        if (remaining > 0) {
            msg.sender.transfer(remaining);
        }

        preSaleLimit -= num;
        seedContract.transferFrom(owner, msg.sender, num);
        userPurchaseNumMap[msg.sender] += purchaseMoney;
        Purchase(msg.sender, num, purchaseMoney);
    }

    event WithdrawFee(uint balance);
    /**
        将现金提取到owner地址
     */
    function withdrawFee() public onlyOwner {
        require(this.balance > 0);
        owner.transfer(this.balance);
        WithdrawFee(this.balance);
    }
}
function withdrawFee() public onlyOwner {
    require(this.balance > 0);
    owner.transfer(this.balance);
    WithdrawFee(this.balance);
}

/**
 将现金提取到owner地址
 */