<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import { useEffect, useCallback, useRef } from 'react';

/**
 * Internal dependencies
 */
import { useAPI, useConfig } from '../';
import useUploadVideoFrame from './utils/useUploadVideoFrame';
import useMediaReducer from './useMediaReducer';
import useUploadMedia from './useUploadMedia';
import Context from './context';
import { getResourceFromAttachment } from './utils';

function MediaProvider({ children }) {
  const { state, actions } = useMediaReducer();
  const { media, pagingNum, mediaType, searchTerm } = state;
  const {
    fetchMediaStart,
    fetchMediaSuccess,
    fetchMediaError,
    resetFilters,
    setMedia,
    setMediaType,
    setSearchTerm,
    setNextPage,
    updateMediaElement,
    deleteMediaElement,
  } = actions;
  const {
    actions: { getMedia },
  } = useAPI();

  const fetchMedia = useCallback(
    (
      {
        searchTerm: currentSearchTerm,
        pagingNum: p = 1,
        mediaType: currentMediaType,
      } = {},
      callback
    ) => {
      fetchMediaStart({ pagingNum: p });
      getMedia({
        mediaType: currentMediaType,
        searchTerm: currentSearchTerm,
        pagingNum: p,
      })
        .then(({ data, headers }) => {
          const totalPages = parseInt(headers.get('X-WP-TotalPages'));
          const mediaArray = data.map(getResourceFromAttachment);
          callback({
            media: mediaArray,
            mediaType: currentMediaType,
            searchTerm: currentSearchTerm,
            pagingNum: p,
            totalPages,
          });
        })
        .catch(fetchMediaError);
    },
    [fetchMediaError, fetchMediaStart, getMedia]
  );

  const { uploadMedia, isUploading } = useUploadMedia({ media, setMedia });
  const { uploadVideoFrame } = useUploadVideoFrame({
    updateMediaElement,
  });

  const {
    allowedMimeTypes: { video: allowedVideoMimeTypes },
  } = useConfig();

  const stateRef = useRef();
  stateRef.current = state;

  const resetWithFetch = useCallback(() => {
    // eslint-disable-next-line no-shadow
    const { mediaType, pagingNum, searchTerm } = stateRef.current;

    resetFilters();
    if (!mediaType && !searchTerm && pagingNum === 1) {
      fetchMedia({ mediaType }, fetchMediaSuccess);
    }
  }, [fetchMedia, fetchMediaSuccess, resetFilters]);

  useEffect(() => {
    fetchMedia({ searchTerm, pagingNum, mediaType }, fetchMediaSuccess);
  }, [fetchMedia, fetchMediaSuccess, mediaType, pagingNum, searchTerm]);

  const processing = useRef([]);
  const processed = useRef([]);
  const uploadVideoPoster = useCallback(
    (id, src) => {
      const process = async () => {
        if (processed.current.includes(id) || processing.current.includes(id)) {
          return;
        }
        processing.current.push(id);
        try {
          await uploadVideoFrame(id, src);
          processed.current.push(id);
        } finally {
          processing.current.remove(id);
        }
      };
      process();
    },
    [uploadVideoFrame]
  );

  const processor = useCallback(
    ({ mimeType, posterId, id, src, local }) => {
      const process = async () => {
        if (<commit_msg>Update processing.current.remove to processing.current.filter<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import { useEffect, useCallback, useRef } from 'react';

/**
 * Internal dependencies
 */
import { useAPI, useConfig } from '../';
import useUploadVideoFrame from './utils/useUploadVideoFrame';
import useMediaReducer from './useMediaReducer';
import useUploadMedia from './useUploadMedia';
import Context from './context';
import { getResourceFromAttachment } from './utils';

function MediaProvider({ children }) {
  const { state, actions } = useMediaReducer();
  const { media, pagingNum, mediaType, searchTerm } = state;
  const {
    fetchMediaStart,
    fetchMediaSuccess,
    fetchMediaError,
    resetFilters,
    setMedia,
    setMediaType,
    setSearchTerm,
    setNextPage,
    updateMediaElement,
    deleteMediaElement,
  } = actions;
  const {
    actions: { getMedia },
  } = useAPI();

  const fetchMedia = useCallback(
    (
      {
        searchTerm: currentSearchTerm,
        pagingNum: p = 1,
        mediaType: currentMediaType,
      } = {},
      callback
    ) => {
      fetchMediaStart({ pagingNum: p });
      getMedia({
        mediaType: currentMediaType,
        searchTerm: currentSearchTerm,
        pagingNum: p,
      })
        .then(({ data, headers }) => {
          const totalPages = parseInt(headers.get('X-WP-TotalPages'));
          const mediaArray = data.map(getResourceFromAttachment);
          callback({
            media: mediaArray,
            mediaType: currentMediaType,
            searchTerm: currentSearchTerm,
            pagingNum: p,
            totalPages,
          });
        })
        .catch(fetchMediaError);
    },
    [fetchMediaError, fetchMediaStart, getMedia]
  );

  const { uploadMedia, isUploading } = useUploadMedia({ media, setMedia });
  const { uploadVideoFrame } = useUploadVideoFrame({
    updateMediaElement,
  });

  const {
    allowedMimeTypes: { video: allowedVideoMimeTypes },
  } = useConfig();

  const stateRef = useRef();
  stateRef.current = state;

  const resetWithFetch = useCallback(() => {
    // eslint-disable-next-line no-shadow
    const { mediaType, pagingNum, searchTerm } = stateRef.current;

    resetFilters();
    if (!mediaType && !searchTerm && pagingNum === 1) {
      fetchMedia({ mediaType }, fetchMediaSuccess);
    }
  }, [fetchMedia, fetchMediaSuccess, resetFilters]);

  useEffect(() => {
    fetchMedia({ searchTerm, pagingNum, mediaType }, fetchMediaSuccess);
  }, [fetchMedia, fetchMediaSuccess, mediaType, pagingNum, searchTerm]);

  const processing = useRef([]);
  const processed = useRef([]);
  const uploadVideoPoster = useCallback(
    (id, src) => {
      const process = async () => {
        if (processed.current.includes(id) || processing.current.includes(id)) {
          return;
        }
        processing.current.push(id);
        try {
          await uploadVideoFrame(id, src);
          processed.current.push(id);
        } finally {
          processing.current = processing.current.filter((e) => e !== id);
        }
      };
      process();
    },
    [uploadVideoFrame]
  );

  const processor = useCallback(
    ({ mimeType, posterId, id, src, local }) => {
      const process = async () => {
        if (
{'fraction_non_alphanumeric': 0.11666234103296133, 'fraction_numerical': 0.0025953802232026994, 'mean_word_length': 2.8515742128935533, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 20, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3513722', 'n_tokens_mistral': 2137, 'n_tokens_neox': 2109, 'n_words': 580}