import { code } from 'dashboard/generated/controlplane';
import { createServices } from 'dashboard/generated/controlplane/twirp';
import * as _ from 'lodash';
import { useEffect, useState } from 'react';
import { GetControlplaneEndpoint } from './env';

import twirp = code.justin.tv.eventbus.controlplane;

export const useCloudformationVersion = (arn: string) => {
  const [version, setVersion] = useState<string>('unknown');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const iamRole = new twirp.IAMRole({ arn });
  const getCloudformationVersionReq = new twirp.GetCloudFormationVersionReq({
    iamRole,
  });

  const client = createServices(GetControlplaneEndpoint());

  useEffect(() => {
    if (_.isNil(arn) || arn === '') {
      return;
    }
    const fetchData = async () => {
      try {
        const resp = await client.getCloudFormationVersion(
          getCloudformationVersionReq,
        );
        setVersion(resp.version);
        setLoading(false);
      } catch (err) {
        setLoading(false);
        setError(err);
      }
    };
    fetchData();
  }, [arn]);

  return { version, loading, error };
};
