import EIP712Domain from "eth-typed-data";
import { SimpleSigner } from "did-jwt";
import { ethers } from "ethers";

import {
  useGnosisApi,
  useIsGnosisSafeDeployed,
  useGnosisEstimateTransaction,
} from "../../session";

const { utils } = ethers;

try {
  const { safe } = gnosisSafe;

  // https://github.com/gnosis/safe-demo/blob/master/scripts/demo.js
  const { publicAddress, privateKey } = myWallet;

  console.log({ publicAddress});

  const isDeployed = await isGnosisSafeDeployed({ safe });

  if (!isDeployed) {
    throw new Error(`The gnosisSafe at address ${safe} has not been initialized with a payment of ${gnosisSafe.payment}wei.`);
  }
  
  // Taken from: https://github.com/gnosis/safe-demo/blob/master/scripts/demo.js
  const GnosisWalletRequest = EIP712Domain.fromSignatureRequest(
    {
      types: {
        EIP712Domain: [
          { type: "address", name: "verifyingContract" }
        ],
        SafeTx: [
          { type: "address", name: "to" },
          { type: "uint256", name: "value" },
          { type: "bytes", name: "data" },
          { type: "uint8", name: "operation" },
          { type: "uint256", name: "safeTxGas" },
          { type: "uint256", name: "dataGas" },
          { type: "uint256", name: "gasPrice" },
          { type: "address", name: "gasToken" },
          { type: "address", name: "refundReceiver" },
          { type: "uint256", name: "nonce" },
        ]
      },
      domain: {
        verifyingContract: "0x39cBD3814757Be997040E51921e8D54618278A08",
      },
      primaryType: "SafeTx",
      message: {
        to: "0x39cBD3814757Be997040E51921e8D54618278A08",
        value: "10000000000000000",
        data: "0x",
        operation: "0",
        safeTxGas: "42671",
        dataGas: "40660",
        gasPrice: "10000000000",
        gasToken: "0x0000000000000000000000000000000000000000",
        refundReceiver: "0x0000000000000000000000000000000000000000",
        nonce: "0"
      }
    },
  );

  const { SafeTx } = GnosisWalletRequest.domain.types;

  const to = utils.getAddress("0x3cb0660b9419b06521aed844ad6d5a7b355bd055");

  const baseTxn = {
    to,
    value: "1000",
    data: "0x",
    nonce: "0",
    operation: "0",
  };

  const { safeTxGas, dataGas, gasPrice, gasToken, refundReceiver } = await gnosisEstimateTransaction(
    safe,
    baseTxn,
  );

  const txn = {
    ...baseTxn,
    safeTxGas,
    dataGas,
    gasPrice,
    gasToken,
    refundReceiver,
  };

  const safeTx = new SafeTx(txn);

  const signer = new SimpleSigner(`${privateKey}`);
  const { r, s, recoveryParam: v } = await safeTx.sign(signer);

  const signature = {
    r: new BigNumber(`0x${r}`, 16).toString(10),
    s: new BigNumber(`0x${s}`, 16).toString(10),
    v,
  };

  const { data: x } = await gnosis({
    url: `/v1/safes/${safe}/transactions/`,
    method: "post",
    data: {
      ...txn,
      signatures: [signature],
    },
  }); // Throws: "InvalidOwners: ('Signers=%s are not valid owners of the safe...)"

} catch (e) {
  console.error(e);
}
