import { Text, View } from 'react-native'
//components
import Header from "../../components/Header"
import { ArrowBack } from "../styles/page";
import { Ingredients } from "../../components/recipes/addRecipe/Inputs";
//styling
import { Wrapper, WrapperRecipe, Input, InputInstructions, IconRecipe, IconPot, IconMeal, IconImage, IconCheck } from "./styles/addRecipe"
import { useState } from "react";
import { addRecipe, findRecipeById, updateRecipe } from "../../redux/slices/recipesSlice";
import { useDispatch, useSelector } from "react-redux";
import { StyledImage } from "./styles/recipe";
import HeaderPadding from '../../components/Header';
const AddRecipe = () => {
let { id } = useParams()
const foundRecipe = useSelector(state => findRecipeById(state, id))
let recipe = foundRecipe ? foundRecipe : { name: '', prepTime: '', servings: '', image: '', ingredients: [], instructions: '' }
const dispatch = useDispatch()
const [name, setName] = useState(recipe.name)
const [prepTime, setPrepTime] = useState(recipe.prepTime)
const [servings, setServings] = useState(recipe.servings)
const [image, setImage] = useState(recipe.image)
const [ingredients, setIngredients] = useState(recipe.ingredients)
const [instructions, setInstructions] = useState(recipe.instructions)
const handleImageInput = (input) => {
if (input.target.files && input.target.files[0] && input.target.files[0].size < 1000000) {
let reader = new FileReader()
reader.onload = function (e) {
setImage(e.target.result)
};
reader.readAsDataURL(input.target.files[0])
}
else {
alert("That file is too big! Choose an image with a size lower than 1MB")
}
}
const submitRecipe = () => {
if (name && ingredients && instructions) {
foundRecipe ? dispatch(updateRecipe({ _id: foundRecipe._id, name, prepTime: Number(prepTime), servings: Number(servings), image, ingredients, instructions }))
: dispatch(addRecipe({ name, prepTime: Number(prepTime), servings: Number(servings), image, ingredients, instructions }))
console.log(typeof (image))
}
else {
alert("You should add a name, at least one ingredient and the instructions")
}
}
const handleInput = (event) => {
let lastChar = event.target.value.substr(-1).charCodeAt(0);
let penultimateChar = event.target.value.substr(-2).charCodeAt(0);
if (instructions === '') {
setInstructions("- " + event.target.value)
return
}
else if (penultimateChar === 10 && lastChar === 45) {
setInstructions(instructions.slice(0, instructions.length - 3))
return
}
else if (lastChar === 10) {
setInstructions(event.target.value + "- ")
return
}
setInstructions(event.target.value)
}
return (
<>
{image && }
setName(text.target.value)}
placeholder="Recipe name" />
setPrepTime(text.target.value)}
placeholder="Prep time (min)" />
setServings(text.target.value)}
placeholder="Servings" />
handleImageInput(input)} />
handleInput(text)}
placeholder='Instructions' />
>
)
}
export default AddRecipe