import { Meta, Story, Canvas } from '@storybook/addon-docs/blocks';
import { FileUploaderV2 } from './file-uploader-v2.component';

<Meta title="Components/Inputs/FileUploaderV2" component={FileUploaderV2} />

# File Uploader

This component allows a user to upload files other via dropping a file into the "zone" or by clicking on the prompt and selecting a file from the file dialog.

## Without Files

<Canvas>
  <Story id="components-inputs-fileuploaderv2--without-files" />
</Canvas>

## With Files

<Canvas>
  <Story id="components-inputs-fileuploaderv2--with-files" />
</Canvas>

## With Error

<Canvas>
  <Story id="components-inputs-fileuploaderv2--with-error" />
</Canvas>

## Interactive

<Canvas>
  <Story id="components-inputs-fileuploaderv2--interactive" />
</Canvas>

## Usage

Uploading a file will trigger `onDrop`. Removing a file will trigger `onClickRemoveHandler`.

The `acceptedFileTypes` should be a comma separated string of extensions (including the period).

### Reading a file

In order to read a file, it is recommended to use the `promise-file-reader` package.

You can then:

```js
// Example: https://github.com/wealthsimple/marketing-ui/blob/master/src/portfolio-review/store/portfolio-review-wizard/portfolio-review-wizard.actions.js#L40-L63

import { readAsDataURL } from 'promise-file-reader';

const content = readAsDataURL(attachment);
// content will be a base64 encoded version of the file
```

### Decoding a file

When you send a file to a server, you may want to upload it to `DocumentService`.

Assuming you sent the encoded content and the filename as mentioned above, you could do so like this:

This will require decoding the file:

```rb
// Example: https://github.com/wealthsimple/review/blob/master/app/services/attachment_uploader.rb

def decode_data_url(data_url)
  start = data_url.index(';base64,') + 8
  file_content = data_url[start..-1]
  Base64.decode64(file_content)
end

def upload_attachment_to_document_service(attachment)
  extension = File.extname(attachment['filename'])
  new_document = DocumentService::Document.new!(
    filename: "#{@prospect.canonical_id}-statement-#{UUID.generate(5)}#{extension}", # Modify as desired
  )
  RestClient.put(new_document.upload_url, decode_data_url(attachment['content']))
  DocumentService::Document.create!({
    resource_type: 'Prospect', # Change to the right resource type
    resource_id: @prospect.canonical_id, # Change to the right resource ID
    s3_key: new_document.s3_key,
    document_type: 'prospect_investment_statement', # Change to the right document type
    date: Date.today,
  })
end
```

### Appendix

React Dropzone - https://react-dropzone.js.org/
