import React from 'react'
import { Meta } from '@storybook/react/types-6-0'
import { Story } from '@storybook/react'
import { FileInput,FileInputProps } from './FileInput'
import axios from 'axios'

export default {
  title:'Components/FileInput',
  component: FileInput,
  argTypes: {}
} as Meta

const Template: Story<FileInputProps> = (args) => {
  const onUpload = async (files: File[]) => {
    const fileType = files[0].type
    if (fileType === 'image/png' || fileType === 'image/jpg') {
      const url = 'https://europe-west2-unomii.cloudfunctions.net/api/image/'
      const authToken = 'Bearer somethingSecret'
      const base64 = await convertToBase64(files[0])
      const body = {
        image: base64,
        name: files[0].name
      }
      const response = await axios.post(url, body , { headers: { 'Authorization': authToken } })
      if(response.status !== 200) 
        alert('Error happened!')
      
      else 
        alert('Succesfully received your image')
      
    }
  }

  const convertToBase64 = (file:File) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader()
      fileReader.readAsDataURL(file)
      fileReader.onload = () => {
        resolve(fileReader.result)
      }
      fileReader.onerror = (error) => {
        reject(error)
      }
    })
  }

  return (
    <FileInput 
      {...args} 
      onUpload={onUpload} 
    />
  )
}

export const Basic = Template.bind({})
Basic.args = { formats:['jpg', 'png'] }


  
    
  
    
  