/*
 * This component is built using `gatsby-image` to automatically serve optimized
 * images with lazy loading and reduced file sizes. The image is loaded using a
 * `StaticQuery`, which allows us to load the image from directly within this
 * component, rather than having to pass the image data down from pages.
 *
 * For more information, see the docs:
 * - `gatsby-image`: https://gatsby.app/gatsby-image
 * - `StaticQuery`: https://gatsby.app/staticquery
 */

import React from 'react'
import { StaticQuery, graphql } from 'gatsby'
import Img from 'gatsby-image'
import styled from 'styled-components'
import R from 'ramda'

interface DataType {
  allFile: AllFileType
}

interface AllFileType {
  edges: EdgesType[]
}

interface EdgesType {
  node: NodeType
}

interface NodeType {
  childImageSharp: FluidType
  relativePath: string
  name: string
}

interface FluidType {
  fluid: any;
}

type AdditionalImageProps = {
  maxWidth?: string
  src?: string
}

type ChangedImageProps = Record<
  Exclude<keyof AdditionalImageProps, 'src'>,
  string
>

const StyledDiv = styled.div.attrs<AdditionalImageProps, ChangedImageProps>({
  maxWidth: props => props.maxWidth || `320px`,
})`
  max-width: ${props => props.maxWidth};
`

const Image: React.FunctionComponent<AdditionalImageProps> = props => (
  <StaticQuery
    query={graphql`
      query {
        allFile(filter: { extension: { eq: "png" } }) {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={(data: DataType) => {
      const index = R.findIndex(
        R.includes(props.src),
        R.map((n: EdgesType) => n.node.relativePath)(data.allFile.edges)
      )
      const image = data.allFile.edges[index];

      return <StyledDiv {...props}>
        <Img fluid={image.node.childImageSharp.fluid} />
      </StyledDiv>
    }}
  />
)

export default Image
