/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* eslint-disable react-hooks/rules-of-hooks */
import { useState, useEffect } from "react";

const errorMessage =
  "matchMedia is not supported, this could happen both because window.matchMedia is not supported by" +
  " your current browser or you're using the useMediaQuery hook whilst server side rendering.";

/**
 * Accepts a media query string then uses the
 * [window.matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) API to determine if it
 * matches with the current document.<br />
 * It also monitor the document changes to detect when it matches or stops matching the media query.<br />
 * Returns the validity state of the given media query.
 *
 */
const useMediaQuery = (mediaQuery: string) => {
  if (!window.matchMedia) {
    // eslint-disable-next-line no-console
    console.warn(errorMessage);
    return false;
  }

  const [isMatch, setIsMatch] = useState(matchMediaQuery(mediaQuery));

  useEffect(() => {
    const mediaQueryList = window.matchMedia(mediaQuery);
    const documentChangeHandler = () => setIsMatch(!!mediaQueryList.matches);

    if (mediaQueryList.addEventListener)
      mediaQueryList.addEventListener("change", documentChangeHandler);
    else mediaQueryList.addListener(documentChangeHandler);

    documentChangeHandler();
    return () => {
      if (mediaQueryList.removeEventListener)
        mediaQueryList.removeEventListener("change", documentChangeHandler);
      else mediaQueryList.removeListener(documentChangeHandler);
    };
  }, [mediaQuery]);

  return isMatch;
};

export default useMediaQuery;

export const matchMediaQuery = (mediaQuery: string) =>
  !!window.matchMedia(mediaQuery).matches;
