import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import LanguageComponent from "./LanguageComponent";

const LanguageContainer = () => {
  const [anchorEl, setAnchorEl] = useState(null);

  const { i18n } = useTranslation();
  const [flag, setFlag] = useState({
    name: "RO",
    alt: "-"
  });

  useEffect(() => {
    if (!i18n.language) return;
    setFlag({
      name: i18n.language === "en" ? "GB" : i18n.language.toUpperCase(),
      alt: i18n.language
    });
  }, [i18n.language]);

  const handleMenuOpen = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLanguageChange = (language) => () => {
    if (language !== i18n.language) {
      i18n.changeLanguage(language);
    }
    setAnchorEl(null);
  };

  const getFlagsPath = () => {
    const basePath = "flags";
    if (process.env.PUBLIC_URL) {
      return `${process.env.PUBLIC_URL}/${basePath}`;
    } else {
      return basePath;
    }
  };

  return (
    <LanguageComponent
      languageIsSet={i18n.language ? true : false}
      anchorEl={anchorEl}
      onMenuOpen={handleMenuOpen}
      onLanguageChange={handleLanguageChange}
      onClose={handleClose}
      flag={flag}
      getFlagsPath={getFlagsPath}
    />
  );
};

export default LanguageContainer;
