contract CryptoCrystal is Sellable, EOACallable, CrystalWeightManager {
    PickaxeIF public pickaxe;
    CrystalBaseIF public crystal;
    ExchangeBaseIF public exchange;
    RandomGeneratorIF public generator;

    //event RandomGenerated(uint256 number);

    event MineCrystals(
        // miner of the crystal
        address indexed owner,
        // time of mining
        uint256 indexed minedAt,
        // tokenIds of mined crystals
        uint256[] tokenIds,
        // kinds of mined crystals
        uint256[] kinds,
        // weights of mined crystals
        uint256[] weights,
        // genes of mined crystals
        uint256[] genes
    );

    event MeltCrystals(
        // melter of the crystals
        address indexed owner,
        // time of melting
        uint256 indexed meltedAt,
        // tokenIds of melted crystals
        uint256[] meltedTokenIds,
        // tokenId of newly generated crystal
        uint256 tokenId,
        // kind of newly generated crystal
        uint256 kind,
        // weight of newly generated crystal
        uint256 weight,
        // gene of newly generated crystal
        uint256 gene
    );

    event CreateExchange(
        // id of exchange
        uint256 indexed id,
        // creator of the exchange
        address owner,
        // tokenId of exhibited crystal
        uint256 ownerTokenId,
        // gene of exhibited crystal
        uint256 ownerTokenGene,
        // kind of exhibited crystal
        uint256 ownerTokenKind,
        // weight of exhibited crystal
        uint256 ownerTokenWeight,
        // kind of condition for exchange
        uint256 kind,
        // weight of condition for exchange
        uint256 weight,
        // time of exchange creation
        uint256 createdAt
    );

    event CancelExchange(
        // id of excahnge
        uint256 indexed id,
        // creator of the exchange
        address owner,
        // tokenId of exhibited crystal
        uint256 ownerTokenId,
        // kind of exhibited crystal
        uint256 ownerTokenKind,
        // weight of exhibited crystal
        uint256 ownerTokenWeight,
        // time of exchange cancelling
        uint256 cancelledAt
    );

    event BidExchange(
        // id of exchange
        uint256 indexed id,
        // creator of the exchange
        address owner,
        // tokenId of exhibited crystal
        uint256 ownerTokenId,
        // gene of exhibited crystal
        uint256 ownerTokenGene,
        // kind of exhibited crystal
        uint256 ownerTokenKind,
        // weight of exhibited crystal
        uint256 ownerTokenWeight,
        // exchanger who bid to exchange
        address exchanger,
        // tokenId of crystal to exchange
        uint256 exchangerTokenId,
        // kind of crystal to exchange
        uint256 exchangerTokenKind,
        // weight of crystal to exchange (may not be the same to weight condition)
        uint256 exchangerTokenWeight,
        // time of bidding
        uint256 bidAt
    );

    struct ExchangeWrapper {
        uint256 id;
        address owner;
        uint256 tokenId;
        uint256 kind;
        uint256 weight;
        uint256 createdAt;
    }

    struct CrystalWrapper {
        address owner;
        uint256 tokenId;
        uint256 gene;
        uint256 kind;
        uint256 weight;
    }

    constructor(
        PickaxeIF _pickaxe,
        CrystalBaseIF _crystal,
        ExchangeBaseIF _exchange,
        RandomGeneratorIF _generator,
        address _wallet,
        address _donationWallet,
        uint256 _donationRate
    ) Sellable(_wallet, _donationWallet, _donationRate) public {
        pickaxe = _pickaxe;
        crystal = _crystal;
        exchange = _exchange;
        generator = _generator;
        setEstimatedWeight(0);
    }

    // @dev mineCrystals consists of two basic operations that burn pickaxes and mint crystals.
    // @param _pkxAmount uint256 the amount of tokens to be burned
    function mineCrystals(uint256 _pkxAmount) external onlyEOA {
        address _owner = msg.sender;
        require(pickaxe.balanceOf(msg.sender) >= _pkxAmount);
        require(0 < _pkxAmount && _pkxAmount <= 100);

        uint256 _crystalAmount = _getRandom(5);

        uint256[] memory _tokenIds = new uint256[](_crystalAmount);
        uint256[] memory _kinds = new uint256[](_crystalAmount);
        uint256[] memory _weights = new uint256[](_crystalAmount);
        uint256[] memory _genes = new uint256[](_crystalAmount);

        uint256[] memory _crystalWeightsCumsum = new uint256[](100);
        _crystalWeightsCumsum[0] = crystalWeights[0];
        for(uint256 i = 1; i < 100; i++) {
            _crystalWeightsCumsum[i] = _crystalWeightsCumsum[i - 1].add(crystalWeights[i]);
        }
        uint256 _totalWeight = _crystalWeightsCumsum[_crystalWeightsCumsum.length - 1];
        uint256 _weightRandomSum = 0;
        uint256 _weightSum = 0;

        for(i = 0; i < _crystalAmount; i++) {
            _weights[i] = _getRandom(100);
            _weightRandomSum = _weightRandomSum.add(_weights[i]);
        }

        for(i = 0; i < _crystalAmount; i++) {
            // Kind is decided randomly according to remaining crystal weights.
            // That means crystals of large quantity are chosen with high probability.
            _kinds[i] = _getFirstIndex(_getRandom(_totalWeight), _crystalWeightsCumsum);

            // Weight is decided randomly according to estimatedWeight.
            // EstimatedWeight is fixed (calculated in advance) in one mining.
            // EstimatedWeight is randomly divided into each of weight.
            // That means sum of weights is equal to EstimatedWeight.
            uint256 actualWeight = estimatedWeight.mul(_pkxAmount);
            _weights[i] = _weights[i].mul(actualWeight).div(_weightRandomSum);

            // Gene is decided randomly.
            _genes[i] = _generateGene();

            require(_weights[i] > 0);

            _tokenIds[i] = crystal.mint(_owner, _genes[i], _kinds[i], _weights[i]);

            crystalWeights[_kinds[i]] = crystalWeights[_kinds[i]].sub(_weights[i]);

            _weightSum = _weightSum.add(_weights[i]);
        }

        setEstimatedWeight(_weightSum);
        pickaxe.burn(msg.sender, _pkxAmount);

        emit MineCrystals(
        _owner,
        now,
        _tokenIds,
        _kinds,
        _weights,
        _genes
        );
    }

    // @dev meltCrystals consists of two basic operations.
    //      It burns old crystals and mint new crystal.
    //      The weight of new crystal is the same to total weight of bunred crystals.
    // @notice meltCrystals may have bugs. We will fix later.
    // @param uint256[] _tokenIds the token ids of crystals to be melt
    function meltCrystals(uint256[] _tokenIds) external onlyEOA {
        uint256 _length = _tokenIds.length;
        address _owner = msg.sender;

        require(2 <= _length && _length <= 10);

        uint256[] memory _kinds = new uint256[](_length);
        uint256 _weight;
        uint256 _totalWeight = 0;

        for(uint256 i = 0; i < _length; i++) {
            require(crystal.ownerOf(_tokenIds[i]) == _owner);
            (_kinds[i], _weight) = crystal.getCrystalKindWeight(_tokenIds[i]);
            if (i != 0) {
                require(_kinds[i] == _kinds[i - 1]);
            }

            _totalWeight = _totalWeight.add(_weight);
            crystal.burn(_owner, _tokenIds[i]);
        }

        uint256 _gene = _generateGene();
        uint256 _tokenId = crystal.mint(_owner, _gene, _kinds[0], _totalWeight);

        emit MeltCrystals(_owner, now, _tokenIds, _tokenId, _kinds[0], _totalWeight, _gene);
    }

    // @dev create exchange
    // @param uint256 _tokenId tokenId you want to exchange
    // @param uint256 _kind crystal kind you want to get
    // @param uint256 _weight minimum crystal weight you want to get
    function createExchange(uint256 _tokenId, uint256 _kind, uint256 _weight) external onlyEOA {
        ExchangeWrapper memory _ew = ExchangeWrapper({
            id: 0, // specify after
            owner: msg.sender,
            tokenId: _tokenId,
            kind: _kind,
            weight: _weight,
            createdAt: 0
            });

        CrystalWrapper memory _cw = getCrystalWrapper(msg.sender, _tokenId);

        require(crystal.ownerOf(_tokenId) == _cw.owner);
        require(_kind < 100);

        // escrow crystal to exchange contract
        crystal._transferFrom(_cw.owner, exchange, _tokenId);

        _ew.id = exchange.create(_ew.owner, _tokenId, _cw.gene, _cw.kind, _cw.weight, _ew.kind, _ew.weight, now);

        emit CreateExchange(_ew.id, _ew.owner, _ew.tokenId, _cw.gene, _cw.kind, _cw.weight, _ew.kind, _ew.weight, now);
    }

    function getCrystalWrapper(address _owner, uint256 _tokenId) internal returns(CrystalWrapper) {
        CrystalWrapper memory _cw;
        _cw.owner = _owner;
        _cw.tokenId = _tokenId;
        (_cw.gene, _cw.kind, _cw.weight) = crystal.getCrystalGeneKindWeight(_tokenId);
        return _cw;
    }

    // @dev cancel exchange
    // @param uint256 _id exchangeId you want to cancel
    function cancelExchange(uint256 _id) external onlyEOA {
        require(exchange.ownerOf(_id) == msg.sender);

        uint256 _tokenId = exchange.getTokenId(_id);

        CrystalWrapper memory _cw = getCrystalWrapper(msg.sender, _tokenId);

        // withdraw crystal from exchange contract
        crystal._transferFrom(exchange, _cw.owner, _cw.tokenId);

        exchange.remove(_id);

        emit CancelExchange(_id, _cw.owner, _cw.tokenId, _cw.kind, _cw.weight, now);
    }

    // @dev bid exchange
    // @param uint256 _exchangeId exchange id you want to bid
    // @param uint256 _tokenId token id of your crystal to be exchanged
    function bidExchange(uint256 _exchangeId, uint256 _tokenId) external onlyEOA {
        // exchange
        ExchangeWrapper memory _ew;
        _ew.id = _exchangeId;
        (_ew.owner, _ew.tokenId, _ew.kind, _ew.weight, _ew.createdAt) = exchange.getExchange(_ew.id); // check existence

        // crystal of exchanger
        CrystalWrapper memory _cwe = getCrystalWrapper(msg.sender, _tokenId);

        // crystal of creator of exchange
        CrystalWrapper memory _cwo = getCrystalWrapper(_ew.owner, _ew.tokenId);

        require(_cwe.owner != _ew.owner);
        require(_cwe.kind == _ew.kind);
        require(_cwe.weight >= _ew.weight);

        // transfer my crystal to owner of exchange
        crystal._transferFrom(_cwe.owner, _ew.owner, _cwe.tokenId);

        // transfer escrowed crystal to me.
        crystal._transferFrom(exchange, _cwe.owner, _ew.tokenId);

        exchange.remove(_ew.id);

        emit BidExchange(_ew.id, _ew.owner, _ew.tokenId, _cwo.gene, _cwo.kind, _cwo.weight, _cwe.owner, _cwe.tokenId, _cwe.kind, _cwe.weight, now);
    }

    // @dev get index when cumsum[i] exceeds _in first.
    // @param uint256 _min
    // @param uint256[] _sorted array is required to be sorted by ascending order
    function _getFirstIndex(uint256 _min, uint256[] _sorted) public pure returns(uint256) {
        for(uint256 i = 0; i < _sorted.length; i++) {
            if(_min < _sorted[i]) {
                return i;
            }
        }
        return _sorted.length - 1;
    }

    function _transferFromOwner(address _to, uint256 _value) internal {
        pickaxe.transferFromOwner(_to, _value);
    }

    function _generateGene() internal returns(uint256) {
        return _getRandom(~uint256(0));
    }

    function _getRandom(uint256 _max) public returns(uint256){
        bytes32 hash = keccak256(generator.generate());
        uint256 number = (uint256(hash) % _max) + 1;
        //emit RandomGenerated(number);
        return number;
    }

    // @dev change random generator
    // @param RandomGeneratorIF randomGenerator contract address
    function setRandomGenerator(RandomGeneratorIF _generator) external onlyOwner {
        generator = _generator;
    }
}
// @title CryptoCrystal
// @author Takayuki Jimba
// @dev Almost all application specific logic is in this contract.
//      CryptoCrystal acts as a facade to Pixaxe(ERC20), CrystalBase(ERC721), ExchangeBase as to transactions.
function setRandomGenerator(RandomGeneratorIF _generator) external onlyOwner {
    generator = _generator;
}

// @dev change random generator
// @param RandomGeneratorIF randomGenerator contract address