/*
 * Copyright ConsenSys AG.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
package org.hyperledger.besu.ethereum.mainnet.precompiles;

import static org.hyperledger.besu.nativelib.altbn128.LibAltbn128.altbn128_add_precompiled;

import org.hyperledger.besu.crypto.altbn128.AltBn128Point;
import org.hyperledger.besu.crypto.altbn128.Fq;
import org.hyperledger.besu.ethereum.core.Gas;
import org.hyperledger.besu.ethereum.mainnet.AbstractPrecompiledContract;
import org.hyperledger.besu.ethereum.vm.GasCalculator;
import org.hyperledger.besu.ethereum.vm.MessageFrame;

import java.math.BigInteger;
import java.util.Arrays;

import com.sun.jna.ptr.IntByReference;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.MutableBytes;

public class AltBN128AddPrecompiledContract extends AbstractPrecompiledContract {

  private final Gas gasCost;

  private AltBN128AddPrecompiledContract(final GasCalculator gasCalculator, final Gas gasCost) {
    super("AltBN128Add", gasCalculator);
    this.gasCost = gasCost;
  }

  public static AltBN128AddPrecompiledContract byzantium(final GasCalculator gasCalculator) {
    return new AltBN128AddPrecompiledContract(gasCalculator, Gas.of(500));
  }

  public static AltBN128AddPrecompiledContract istanbul(final GasCalculator gasCalculator) {
    return new AltBN128AddPrecompiledContract(gasCalculator, Gas.of(150));
  }

  @Override
  public Gas gasRequirement(final Bytes input) {
    return gasCost;
  }

  @Override
  public Bytes compute(final Bytes input, final MessageFrame messageFrame) {
    if (AltBN128PairingPrecompiledContract.useNative) {
      return computeNative(input);
    } else {
      return computeDefault(input);
    }
  }

  private static Bytes computeDefault(final Bytes input) {
    final BigInteger x1 = extractParameter(input, 0, 32);
    final BigInteger y1 = extractParameter(input, 32, 32);
    final BigInteger x2 = extractParameter(input, 64, 32);
    final BigInteger y2 = extractParameter(input, 96, 32);

    final AltBn128Point p1 = new AltBn128Point(Fq.create(x1), Fq.create(y1));
    final AltBn128Point p2 = new AltBn128Point(Fq.create(x2), Fq.create(y2));
    if (!p1.isOnCurve() || !p2.isOnCurve()) {
      return null;
    }
    final AltBn128Point sum = p1.add(p2);
    final Bytes x = sum.getX().toBytes();
    final Bytes y = sum.getY().toBytes();
    final MutableBytes result = MutableBytes.create(64);
    x.copyTo(result, 32 - x.size());
    y.copyTo(result, 64 - y.size());

    return result;
  }

  private static Bytes computeNative(final Bytes input) {
    final byte[] output = new byte[64];
    final IntByReference outputSize = new IntByReference(64);
    if (altbn128_add_precompiled(input.toArrayUnsafe(), input.size(), output, outputSize) == 0) {
      return Bytes.wrap(output, 0, outputSize.getValue());
    } else {
      return null;
    }
  }

  private static BigInteger extractParameter(
      final Bytes input, final int offset, final int length) {
    if (offset > input.size() || length == 0) {
      return BigInteger.ZERO;
    }
    final byte[] raw = Arrays.copyOfRange(input.toArray(), offset, offset + length);
    return new BigInteger(1, raw);
  }
}