/*
 * 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 { useRef, useEffect } from 'react';
import styled from 'styled-components';

/**
 * Internal dependencies
 */
import { elementFillContent } from '../shared';
import { getMediaSizePositionProps } from '../media';
import StoryPropTypes from '../../types';
import { useStory } from '../../app/story';
import { getBackgroundStyle, videoWithScale } from './util';

const Element = styled.div`
  ${elementFillContent}
  overflow: hidden;
`;

const Video = styled.video`
  position: absolute;
  max-width: initial;
  max-height: initial;
  ${videoWithScale}
`;

function VideoDisplay({
  box: { width, height },
  element: {
    id,
    resource,
    isBackground,
    scale,
    focalX,
    focalY,
    loop,
    isPlaying,
  },
}) {
  let style = {};
  if (isBackground) {
    const styleProps = getBackgroundStyle();
    style = {
      ...style,
      ...styleProps,
    };
  }

  const {
    state: { selectedElementIds },
    actions: { updateElementById },
  } = useStory();

  const videoProps = getMediaSizePositionProps(
    resource,
    width,
    height,
    scale,
    focalX,
    focalY
  );

  const videoRef = useRef();
  const isElementSelected = selectedElementIds.includes(id);

  useEffect(() => {
    if (isPlaying && !isElementSelected && videoRef) {
      updateElementById({
        elementId: id,
        properties: { isPlaying: false },
      });
      videoRef.current.currentTime = 0;
    }
  }, [isPlaying, isElementSelected, videoRef, updateElementById, id]);

  useEffect(() => {
    const ref = videoRef.current;
    const handler = () => {
      updateElementById({
        elementId: id,
        properties: { isPlaying: false },
      });
      videoRef.current.currentTime = 0;
    };
    ref.addEventListener('ended', handler);
    return () => ref.removeEventListener('ended', handler);
  }, [id, updateElementById]);

  useEffect(() => {
    if (isPlaying) {
      videoRef.current.play().catch(() => {
        updateElementById({
          elementId: id,
          properties: { isPlaying: false },
        });
      });
    } else {
      videoRef.current.pause();
    }
  }, [id, videoRef, isPlaying, updateElementById]);

  return (
    <Element>
      <Video
        ref={videoRef}
        poster={resource.poster}
        style={style}
        {...videoProps}
        loop={loop}
      >
        <source src={resource.src} type={resource.mimeType} />
      </Video>
    </Element>
  );
}

VideoDisplay.propTypes = {
  element: StoryPropTypes.elements.video.isRequired,
  box: StoryPropTypes.box.isRequired,
};

export default VideoDisplay;

@@ -1819,16 +1819,73 @@
 des(id);
+%0A  const noElementsSelected = !selectedElementIds.length;
 %0A%0A  useE
@@ -1919,16 +1919,29 @@
 ying && 
+videoRef && (
 !isEleme
@@ -1951,27 +1951,38 @@
 elected 
-&& videoRef
+%7C%7C noElementsSelected)
 ) %7B%0A    
@@ -2130,16 +2130,21 @@
 %7D%0A  %7D, %5B
+%0A    
 isPlayin
@@ -2145,16 +2145,20 @@
 Playing,
+%0A   
  isEleme
@@ -2168,16 +2168,44 @@
 elected,
+%0A    noElementsSelected,%0A   
  videoRe
@@ -2206,16 +2206,20 @@
 ideoRef,
+%0A   
  updateE
@@ -2229,19 +2229,27 @@
 entById,
- id
+%0A    id,%0A  
 %5D);%0A%0A  u

Stop video when nothing is selected