import React from 'react';

import { fetchCameraDevice } from '../../services/map-device';

// 不想放model里面
// 此处如果有需求可以做一个loading
const MapDeviceInject: React.FC = props => {
  const { children, ...rest } = props;
  const [devices, setDevices] = React.useState();
  const [injected, setInjected] = React.useState(false);
  React.useEffect(() => {
    fetchCameraDevice().then(({ code, data }) => {
      if (code === 0) {
        setDevices(data?.list);
        setInjected(true);
      }
    });
  }, []);

  const renderChildren = () => {
    if (typeof children === 'function') {
      return children(devices, rest);
    } else {
      return React.Children.map(children, (child: any) =>
        React.cloneElement(child, { ...rest }),
      );
    }
  };

  // eslint-disable-next-line
  return <>{injected ? renderChildren() : ''}</>;
};

export default MapDeviceInject;
