import { useReminder } from "./ReminderContext";
import { useFlash } from "../App/FlashContext";

export const Attachment = () => {
    const [{ attachment_name }, setReminder] = useReminder();

    const flash = useFlash();

    return (
        <div class="file is-small is-boxed">
            <label class="file-label">
                <input
                    class="file-input"
                    type="file"
                    name="attachment"
                    onInput={async (ev) => {
                        const input = ev.currentTarget;

                        let file = input.files[0];

                        if (file.size >= 8 * 1024 * 1024) {
                            flash({ message: "File too large (max. 8MB).", type: "error" });
                            return;
                        }

                        let attachment: string = await new Promise((resolve) => {
                            let fileReader = new FileReader();
                            fileReader.onload = () => resolve(fileReader.result as string);
                            fileReader.readAsDataURL(file);
                        });
                        attachment = attachment.split(",")[1];
                        const attachment_name = file.name;

                        setReminder((reminder) => ({
                            ...reminder,
                            attachment,
                            attachment_name,
                        }));
                    }}
                ></input>
                <span class="file-cta">
                    <span class="file-label">{attachment_name || "Add Attachment"}</span>
                    <span class="file-icon">
                        <i class="fas fa-upload"></i>
                    </span>
                </span>
            </label>
        </div>
    );
};
