import { useState } from 'react';
import {
  Contracts, RuntimeArgs, CLValueBuilder, CLPublicKey, DeployUtil,
} from 'casper-js-sdk';
import axios from 'axios';
import getProvider from './casper-wallet';

const provider = getProvider();

const NETWORK_NAME = 'casper-test'; // "casper" for mainnet
const CONTRACT_HASH = 'hash-9d6641378c5859e4a0367b37f358d9861496318ba814bdd92903210a3f633198';

const updateMessage = (props, message) => {
  const contract = new Contracts.Contract();
  contract.setContractHash(CONTRACT_HASH);
  const runtimeArguments = RuntimeArgs.fromMap({
    message: CLValueBuilder.string(message),
  });
  const deploy = contract.callEntrypoint(
    'hello',
    runtimeArguments,
    CLPublicKey.fromHex(props.publicKey),
    NETWORK_NAME,
    '1000000000', // 1 CSPR (10^9 Motes)
  );
  const deployJSON = DeployUtil.deployToJson(deploy);
  // Initiates sign request
  provider
    .sign(JSON.stringify(deployJSON), props.publicKey)
    .then((res) => {
      if (res.cancelled) {
        alert('Signing cancelled');
      } else {
        const signedDeploy = DeployUtil.setSignature(
          deploy,
          res.signature,
          CLPublicKey.fromHex(props.publicKey),
        );
        console.log('signedDeploy:', signedDeploy);
        console.log('signedDeploy json:', DeployUtil.deployToJson(signedDeploy));

        axios
          .post('/api/sendDeploy', DeployUtil.deployToJson(signedDeploy), {
            headers: {
              'Content-Type': 'application/json',
            },
          })
          .then((response) => {
            alert(response.data);
          })
          .catch((error) => {
            console.error(error.message);
          });
      }
    })
    .catch((error) => {
      console.error(error.message);
    });
};

function UpdateMessage(props) {
  const [message, setMessage] = useState('');

  return (
    <>
      <input
        id="message"
        type="text"
        value={message}
        onChange={(e) => {
          setMessage(e.target.value);
        }}
      />
      <button type="button" onClick={() => updateMessage(props, message)}>Update Message</button>
    </>
  );
}
export default UpdateMessage;
