import React from 'react';
import { bool, string, arrayOf, shape } from 'prop-types';
import styled, { keyframes } from 'styled-components';
import { COLOR_PRIMARY, STEEL_BLUE } from '@vincent_za/styles';
import { PROP_ASYNC_STATUS, SHAPE_ASYNC_STATUS_INITIAL, determineAsyncStatus } from '@vincent_za/utils';

const transition = keyframes`
  from { left: -20rem; width: 30%; }
  50%  { width: 30%; }
  70%  { width: 70%; }
  80%  { left: 50%; }
  95%  { left: 120%; }
  to   { left: 100%; }
`;

const Wrap = styled.div`
  z-index: 4;
  position: ${props => props.isPageLoader ? 'fixed' : 'absolute'};
  top: 0;
  right: 0;
  left: 0;
  height: ${props => props.isPageLoader ? '3px' : '2px'};
  overflow: hidden;

  &::before {
    content: "";
    display: block;
    position: absolute;
    left: -20rem;
    width: 20rem;
    height: 100%;
    background-color: ${props => props.isPageLoader ? COLOR_PRIMARY : STEEL_BLUE};
    animation: ${transition} 2s linear infinite;
  };
`;

class LineLoader extends React.PureComponent {
  render() {
    const {
      isPageLoader,
      isDisplayOnLoaded,
      asyncStatus,
      asyncStatusList,
      asyncStatusBusyList = asyncStatusList,
      className,
    } = this.props;
    const { isInitial } = determineAsyncStatus({ asyncStatus, asyncStatusList });
    const { isBusy } = determineAsyncStatus({ asyncStatus, asyncStatusList: asyncStatusBusyList });

    return (
      isBusy && ((isDisplayOnLoaded && !isInitial) || !isDisplayOnLoaded) ?
        <Wrap isPageLoader={isPageLoader} isDisplayOnLoaded={isDisplayOnLoaded} className={className} /> : null
    );
  }
}

LineLoader.propTypes = {
  isPageLoader: bool,
  isDisplayOnLoaded: bool,
  asyncStatus: shape(PROP_ASYNC_STATUS),
  asyncStatusList: arrayOf(shape(PROP_ASYNC_STATUS)),
  asyncStatusBusyList: arrayOf(shape(PROP_ASYNC_STATUS)),
  className: string,
};

LineLoader.defaultProps = {
  isPageLoader: false,
  isDisplayOnLoaded: false,
  asyncStatus: SHAPE_ASYNC_STATUS_INITIAL,
  asyncStatusList: [],
  asyncStatusBusyList: undefined,
  className: '',
};

export default LineLoader;

