import React, { useState, useEffect } from 'react';
import http from 'utils/fetch';
import { api } from 'constants/config';

export default function useControlled(screenId) {
  const [controlled, setControlled] = useState(false);

  useEffect(() => {
    let timeId;

    const getScreenControlled = async () => {
      const result = await http.get<{ isControlled: boolean }>(api.remoteControlled, { id: screenId });
      if (result?.isControlled) {
        setControlled(true);
        timeId && clearInterval(timeId);
      }
    };

    timeId = setInterval(() => {
      getScreenControlled();
    }, 10000);

    if (screenId) {
      getScreenControlled();
    }

    return () => {
      clearInterval(timeId);
    };
  }, [screenId]);

  return controlled;
}
