contract FlipNpikToken is Timestamped, StandardToken, DetailedERC20, HasNoEther {
    using SafeMath for uint256;

    // A wallet that will hold tokens
    address public mainWallet;
    // A wallet that is required to unlock reserve tokens
    address public financeWallet;

    // Locked reserve tokens amount is 500M FNP
    uint256 public reserveSize = uint256(500000000).mul(10 ** 18);
    // List of signatures required to unlock reserve tokens
    mapping (address => bool) public reserveHolders;
    // Total amount of unlocked reserve tokens
    uint256 public totalUnlocked = 0;

    // Scheduled for minting reserve tokens amount is 575M FNP
    uint256 public mintSize = uint256(575000000).mul(10 ** 18);
    // Datetime when minting according to schedule becomes available
    uint256 public mintStart;
    // Total amount of minted reserve tokens
    uint256 public totalMinted = 0;    

    /**
    * Describes minting stage structure fields
    * @param start Minting stage start date
    * @param volumt Total tokens available for the stage
    */
    struct MintStage {
        uint256 start;
        uint256 volume;       
    }

    // Array of stages
    MintStage[] public stages;

    /**
    * @dev Event for reserve tokens minting operation logging
    * @param _amount Amount minted
    */
    event MintReserveLog(uint256 _amount);

    /**
    * @dev Event for reserve tokens unlock operation logging
    * @param _amount Amount unlocked
    */
    event UnlockReserveLog(uint256 _amount);

    /**
    * @param _mintStart Datetime when minting according to schedule becomes available
    * @param _mainWallet A wallet that will hold tokens
    * @param _financeWallet A wallet that is required to unlock reserve tokens
    * @param _owner Smart contract owner address
    */
    constructor (uint256 _mintStart, address _mainWallet, address _financeWallet, address _owner)
        DetailedERC20("FlipNpik", "FNP", 18) public {

        require(_mainWallet != address(0), "Main address is invalid.");
        mainWallet = _mainWallet;       

        require(_financeWallet != address(0), "Finance address is invalid.");
        financeWallet = _financeWallet;        

        require(_owner != address(0), "Owner address is invalid.");
        owner = _owner;

        _setStages(_mintStart);
        _setReserveHolders();

        // 425M FNP should be minted initially
        _mint(uint256(425000000).mul(10 ** 18));
    }       

    /**
    * @dev Mints reserved tokens
    */
    function mintReserve() public onlyOwner {
        require(mintStart < _currentTime(), "Minting has not been allowed yet.");
        require(totalMinted < mintSize, "No tokens are available for minting.");
        
        // Get stage based on current datetime
        MintStage memory currentStage = _getCurrentStage();
        // Get amount available for minting
        uint256 mintAmount = currentStage.volume.sub(totalMinted);

        if (mintAmount > 0 && _mint(mintAmount)) {
            emit MintReserveLog(mintAmount);
            totalMinted = totalMinted.add(mintAmount);
        }
    }

    /**
    * @dev Unlocks reserve
    */
    function unlockReserve() public {
        require(msg.sender == owner || msg.sender == financeWallet, "Operation is not allowed for the wallet.");
        require(totalUnlocked < reserveSize, "Reserve has been unlocked.");        
        
        // Save sender's signature for reserve tokens unlock
        reserveHolders[msg.sender] = true;

        if (_isReserveUnlocked() && _mint(reserveSize)) {
            emit UnlockReserveLog(reserveSize);
            totalUnlocked = totalUnlocked.add(reserveSize);
        }        
    }

    /**
    * @dev Executes regular token approve operation and trigger receiver SC accordingly
    * @param _to Address (SC) that should receive approval and be triggerred
    * @param _value Amount of tokens for approve operation
    * @param _data Additional arguments to be passed to the contract
    */
    function approveAndCall(address _to, uint256 _value, bytes _data) public returns(bool) {
        require(super.approve(_to, _value), "Approve operation failed.");

        // Check if destination address is SC
        if (isContract(_to)) {
            TokenReceiver receiver = TokenReceiver(_to);
            return receiver.tokenFallback(msg.sender, _value, _data);
        }

        return true;
    } 

    /**
    * @dev Mints tokens to main wallet balance
    * @param _amount Amount to be minted
    */
    function _mint(uint256 _amount) private returns(bool) {
        totalSupply_ = totalSupply_.add(_amount);
        balances[mainWallet] = balances[mainWallet].add(_amount);

        emit Transfer(address(0), mainWallet, _amount);
        return true;
    }

    /**
    * @dev Configures minting stages
    * @param _mintStart Datetime when minting according to schedule becomes available
    */
    function _setStages(uint256 _mintStart) private {
        require(_mintStart >= _currentTime(), "Mint start date is invalid.");
        mintStart = _mintStart;

        stages.push(MintStage(_mintStart, uint256(200000000).mul(10 ** 18)));
        stages.push(MintStage(_mintStart.add(365 days), uint256(325000000).mul(10 ** 18)));
        stages.push(MintStage(_mintStart.add(2 * 365 days), uint256(450000000).mul(10 ** 18)));
        stages.push(MintStage(_mintStart.add(3 * 365 days), uint256(575000000).mul(10 ** 18)));
    }

    /**
    * @dev Configures unlock signature holders list
    */
    function _setReserveHolders() private {
        reserveHolders[mainWallet] = false;
        reserveHolders[financeWallet] = false;
    }

    /**
    * @dev Finds current stage parameters according to the rules and current date and time
    * @return Current stage parameters (stage start date and available volume of tokens)
    */
    function _getCurrentStage() private view returns (MintStage) {
        uint256 index = 0;
        uint256 time = _currentTime();        

        MintStage memory result;

        while (index < stages.length) {
            MintStage memory activeStage = stages[index];

            if (time >= activeStage.start) {
                result = activeStage;
            }

            index++;             
        }

        return result;
    }

    /**
    * @dev Checks if an address is a SC
    */
    function isContract(address _addr) private view returns (bool) {
        uint256 size;
        // solium-disable-next-line security/no-inline-assembly
        assembly { size := extcodesize(_addr) }
        return size > 0;
    }

    /**
    * @dev Checks if reserve tokens have all required signatures for unlock operation
    */
    function _isReserveUnlocked() private view returns(bool) {
        return reserveHolders[owner] == reserveHolders[financeWallet] && reserveHolders[owner];
    }
}
/**
 * @title FlipNpikToken
 * @dev The FlipNpikToken is a ERC20 token 
 */
function _getCurrentStage() private view returns (MintStage) {
    uint256 index = 0;
    uint256 time = _currentTime();        

    MintStage memory result;

    while (index < stages.length) {
        MintStage memory activeStage = stages[index];

        if (time >= activeStage.start) {
            result = activeStage;
        }

        index++;             
    }

    return result;
}

/**
 * @dev Finds current stage parameters according to the rules and current date and time
 * @return Current stage parameters (stage start date and available volume of tokens)
 */