

import { fetchFollowers } from '../../api';
import createPlainComponent from '../../utils/createPlainComponent';
import renderUserList from '../UserList';

const renderWarning = target => {
  const render = createPlainComponent(
    `<p>Showing at most the first 30 followers</p>`,
  );
  render(target);
};

const render = (target, { username }) => {
  const renderLoadingPlaceholder = createPlainComponent(
    '<div class="user-data__content">Loading...</div>',
  );
  const element = renderLoadingPlaceholder(target);

  fetchFollowers(username).then(response => {
    const userFound = response.status === 200;
    const renderRealInfo = target => {
      renderWarning(target);
      renderUserList(target, { users: response.data.map(user => user.login) });
    };

    const renderInfo = userFound
      ? renderRealInfo
      : createPlainComponent('No such user!');

    element.querySelector('.user-data__content').innerHTML = '';
    renderInfo(element.querySelector('.user-data__content'));
  });
};

export default render;
