Untitled

mail@pastecode.io avatar
unknown
javascript
3 years ago
16 kB
3
Indexable
Never
import React, { useRef, useState, useEffect, Fragment } from 'react'
import { useHistory } from 'react-router-dom'
import { 
	CardForm, 
  VersusgoalHeader,
  VersusgoalImage,
  TeamContainer,
	SubmitButton, 
	CancelButton, 
	ImageContainer, 
	LoadButton,
	FieldError
} from './styles'
import DatePicker from 'react-datepicker'
import "react-datepicker/dist/react-datepicker.css"
import { 
  getRegistrationTeamByTeamCode,
  createRegistrationTeamPlayer,
  createRegistrationTeamPlayerDocBase64
} from '../../../services/teamPlayer'
import { getSession, 
  removePlayerSession
} from '../../../utils/authSessions'
import Logo from '../../../assets/logo.png'
import { Loading } from '../../molecules/spinner/Loading'

export function CreatePlayer() {

  const [session, setSession] = useState(undefined)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const s = getSession()
    setSession(s)
  }, [])

  const history = useHistory()

	const teamcodeRef = useRef(null)
	const nameRef = useRef(null)
	const surnameRef = useRef(null)
	const dniRef = useRef(null)
	const phoneRef = useRef(null)
	const emailRef = useRef(null)
	const inputProfileRef = useRef(null)
	const inputDniRef = useRef(null)

	const [birthday, setBirthday] = useState(new Date())
	useEffect(() => {
		if (birthday) {
			setBirthdayError(undefined)
		}
	}, [birthday])
	const [profileImg, setProfileImg] = useState(undefined)
	const [dniImg, setDniImg] = useState(undefined)

	// Validations
	const [nameError, setNameError] = useState(undefined)
	const [surnameError, setSurnameError] = useState(undefined)
	const [dniError, setDniError] = useState(undefined)
	const [birthdayError, setBirthdayError] = useState(undefined)
	const [phoneError, setPhoneError] = useState(undefined)
	const [emailError, setEmailError] = useState(undefined)
	const [profileImgError, setProfileImgError] = useState(undefined)
	const [dniImgError, setDniImgError] = useState(undefined)

	
	const handleSubmit = async e => {
		e.preventDefault()
    setLoading(true)
		//Validate fields
		clearValidations()
		const newUser = formValidation()
		if (newUser && 
			typeof newUser === 'object' && 
			Object.keys(newUser).length > 0) {
        //check if team exists
        const code = teamcodeRef.current.value
        const regTeam = await getRegistrationTeam(code)
        if (regTeam) {
          //check if dni already exists
          const dniExists = dniAlreadyExists(regTeam.players, newUser.dni)
          if (!dniExists) {
            
            //create player in firestore
            const { id, name, surname, dni, phone, birthday, email, profileImg, dniImg } = newUser
            const regTeamPlayerResult = setRegistrationTeamPlayer(code, {
              id,
              name,
              surname,
              dni,
              phone,
              birthday,
              email
            })
            if (!regTeamPlayerResult) {
              setLoading(false)
              return
            }

            //create PI doc in storage
            const { tournament_id, competition_id } = regTeam
            const regPiDocResult = await setRegistrationTeamPlayerDoc(tournament_id, competition_id, code, id, 'pi', profileImg)
            if (!regPiDocResult) {
              setLoading(false)
              return
            }

            //create DI doc in storage
            const regDiDocResult = await setRegistrationTeamPlayerDoc(tournament_id, competition_id, code, id, 'di', dniImg)
            if (!regDiDocResult) {
              setLoading(false)
              return
            }

            setLoading(false)
            history.replace('/player-reg-success')

          } else {
            //TODO set notifications
            setLoading(false)
            setDniError('El DNI ingresado ya se encuentra registrado.')
          }
        } else {
          //TODO set notifications
          setLoading(false)
        }
    } else {
      setLoading(false)
    }
	}

  const getRegistrationTeam = async code => {
    const registrationTeam = await getRegistrationTeamByTeamCode(code)
    return registrationTeam.exists ? registrationTeam.data() : undefined    
  }

  const dniAlreadyExists = (playersList, dni) => {
    if (playersList && playersList.length > 0) {
      for( const p of playersList ) {
        if (p.dni === dni) return true
      }
      return false
    }
    return false
  }

  const setRegistrationTeamPlayer = async (code, player) => {
    try {
      await createRegistrationTeamPlayer(code, player)
      return true
    } catch (error) {
      return false
    }
  }

  const setRegistrationTeamPlayerDoc = async (tId, cId, code, id, docType, docFile) => {
    try {
      await createRegistrationTeamPlayerDocBase64(tId, cId, code, id, docType, docFile)
      return true
    } catch (error) {
      return false
    }
  }

	const clearValidations = () => {
		setNameError(undefined)
		setSurnameError(undefined)
		setDniError(undefined)
		setPhoneError(undefined)
		setBirthdayError(undefined)
		setEmailError(undefined)
		setProfileImgError(undefined)
		setDniImgError(undefined)
	}

	const formValidation = () => {
		//name
		const name = nameRef.current.value
		if (name && name.length > 0) {
			if (name.length > 30) {
				setNameError('El nombre es demasiado largo.')
				return false
			} 
		} else {
			setNameError('Por favor, complete este campo')
			return false
		}

		//surname
		const surname = surnameRef.current.value
		if (surname && surname.length > 0) {
			if (surname.length > 30) {
				setSurnameError('El apellido es demasiado largo.')
				return false
			} 
		} else {
			setSurnameError('Por favor, complete este campo.')
			return false
		}

		//dni
		const dni = dniRef.current.value
		if (dni && dni.length > 0) {
			if (dni.length > 30) {
				setDniError('El dni es demasiado largo.')
				return false
			} 
		} else {
			setDniError('Por favor, complete este campo.')
			return false
		}

		//phone
		const phone = phoneRef.current.value
		if (phone && phone.length > 0) {
			if (phone.length > 30) {
				setPhoneError('El telefono es demasiado largo.')
				return false
			} 
		} else {
			setPhoneError('Por favor, complete este campo.')
			return false
		}

		//birthday
		if (birthday) {
			if (birthday.length > 40) {
				setBirthdayError('La fecha de nacimiento es demasiado larga.')
				return false
			} 
		} else {
			setBirthdayError('Por favor, complete este campo.')
			return false
		}

		//email
		const email = emailRef.current.value
		if (email && email.length > 0) {
			if (email.length > 40) {
				setEmailError('El email es demasiado largo.')
				return false
			} 
		} else {
			setEmailError('Por favor, complete este campo.')
			return false
		}

		//profile img
		//TODO check if file exists
		if (!profileImg) {
			setProfileImgError('Por favor, cargue una foto de perfil.')
			return false
		}

		//dni img
		//TODO check if file exists
		if (!dniImg) {
			setDniImgError('Por favor, cargue una foto de dni.')
			return false
		}

		//All Validations Ok
		return {
      id: dni,
			name, 
			surname, 
			dni, 
			phone, 
			birthday, 
			email, 
			profileImg, 
			dniImg
		}
	}

	const handleCancel = () => {
    removePlayerSession()
    history.replace('/')
	}

	const handleProfileImgClick = () => {
		inputProfileRef.current.click()
	}

	const handleProfileImgChange = e => {
		const { files } = e.target
    if (files && files.length) {
			const file = files[0]
      let reader = new FileReader()
      //image turned to base64-encoded Data URI.
      reader.readAsDataURL(file)
      reader.name = file.name
      reader.size = file.size
      reader.onload = event => {
        let img = new Image()
        //result is base64-encoded Data URL
        img.src = event.target.result
        //set name (optional) 
        img.name = event.target.name
        //set size (optional)
        img.size = event.target.size
        img.onload = el => {
          const elem = document.createElement('canvas')
          //scale the image to 200 (width) and keep aspect ratio
          const scaleFactor = 200 / el.target.width
          elem.width = 200
          elem.height = el.target.height * scaleFactor
          //draw in canvas
          const ctx = elem.getContext('2d')
          ctx.drawImage(el.target, 0, 0, elem.width, elem.height)
          //get the base64-encoded Data URI from the resize image
          var srcEncoded = ctx.canvas.toDataURL(el.target, 'image/jpeg', 0)
          setProfileImg(srcEncoded)
        }
      }
    }
	}

	const handleDniImgClick = () => {
		inputDniRef.current.click()
	}

	const handleDniImgChange = e => {
		const { files } = e.target;
    if (files && files.length) {
			const file = files[0]
      let reader = new FileReader()
      //image turned to base64-encoded Data URI.
      reader.readAsDataURL(file)
      reader.name = file.name
      reader.size = file.size
      reader.onload = event => {
        let img = new Image()
        //result is base64-encoded Data URL
        img.src = event.target.result
        //set name (optional) 
        img.name = event.target.name
        //set size (optional)
        img.size = event.target.size
        img.onload = el => {
          const elem = document.createElement('canvas')
          //scale the image to 200 (width) and keep aspect ratio
          const scaleFactor = 340 / el.target.width
          elem.width = 340
          elem.height = el.target.height * scaleFactor
          //draw in canvas
          const ctx = elem.getContext('2d')
          ctx.drawImage(el.target, 0, 0, elem.width, elem.height)
          //get the base64-encoded Data URI from the resize image
          var srcEncoded = ctx.canvas.toDataURL(el.target, 'image/jpeg', 0)
          setDniImg(srcEncoded)
        }
      }
	  }
  }

	const handleBirthdayChange = d => {
		setBirthday(d)
	}

	return (
    <Fragment>
      <VersusgoalHeader className='p-3'>
        <VersusgoalImage src={ Logo } alt='Versusgoal Logo'/>
      </VersusgoalHeader>
      <TeamContainer>
        <h2 
          className='h5 m-0 p-2 font-weight-700 text-light'
          > {session && session.team_name && session.team_category ? (
            `${ session.team_name } ${ session.team_category }`
          ) : (
            'No hay un equipo seleccionado'
          )}
        </h2>
      </TeamContainer>
      <CardForm className='p-4 mb-4' onSubmit={ handleSubmit }>

        <div className='mb-3'>
          <label for='name' className='form-label'>Código de Equipo</label>
          <input 
            type='text' 
            className='form-control' 
            id='teamcode' 
            value={ session && session.team_code ? session.team_code : 'No hay un equipo seleccionado' }
            ref={ teamcodeRef } 
            required
            disabled />
        </div>

        <div className='mb-3'>
          <label for='name' className='form-label'>Nombre</label>
          <input type='text' className='form-control' id='name' ref={ nameRef } required />
          {nameError && (
            <FieldError>{ nameError }</FieldError>
          )}
        </div>
        <div className='mb-3'>
          <label for='surname' className='form-label'>Apellido</label>
          <input type='text' className='form-control' id='surname' ref={ surnameRef } required />
          {surnameError && (
            <FieldError>{ surnameError }</FieldError>
          )}
        </div>
        <div className='mb-3'>
          <label for='dni' className='form-label'>Dni</label>
          <input type='number' className='form-control' id='dni' ref={ dniRef } required />
          {dniError && (
            <FieldError>{ dniError }</FieldError>
          )}
        </div>
        <div className='mb-3 d-flex flex-column'>
          <label className='form-label'>Fecha de Nacimiento (dd/mm/aaaa)</label>
          <DatePicker 
            onChange={ handleBirthdayChange }
            selected={ birthday }
            dateFormat='dd/MM/yyyy'
          />
          {birthdayError && (
            <FieldError>{ birthdayError }</FieldError>
          )}
        </div>
        <div className='mb-3'>
          <label for='phone' className='form-label'>Teléfono</label>
          <input type='number' className='form-control' id='phone' ref={ phoneRef } required />
          {phoneError && (
            <FieldError>{ phoneError }</FieldError>
          )}
        </div>
        <div className='mb-3'>
          <label for='email' className='form-label'>Email</label>
          <input type='email' className='form-control' id='email' ref={ emailRef } required />
          {emailError && (
            <FieldError>{ emailError }</FieldError>
          )}
        </div>

        <div className='mb-3 d-flex flex-column'>
          <label className='form-label'>Imagen de Perfil</label>
          <div className='d-flex flex-column align-items-center'>
            <ImageContainer className='d-flex justify-content-center align-items-center mb-2'>
              <input
                style={{ display: 'none' }}
                ref={ inputProfileRef }
                onChange={ handleProfileImgChange }
                type='file'
                accept='image/*'
              />
              {profileImg ? (
                <img 
                  width='100%' 
                  height='100%' 
                  // src={ URL.createObjectURL(profileImg) } 
                  src={ profileImg }
                  alt='profile'
                />
              ) : 'No hay imagen'}
            </ImageContainer>
            <LoadButton 
              type='button'
              className='btn'
              onClick={ handleProfileImgClick }
              >Cargar Imagen (Perfil)
            </LoadButton>
          </div>
          {profileImgError && (
            <FieldError>{ profileImgError }</FieldError>
          )}
        </div>

        <div className='mb-3 d-flex flex-column'>
          <label className='form-label'>Imagen de frente del DNI</label>
          <div className='d-flex flex-column align-items-center'>
            <ImageContainer className='d-flex justify-content-center align-items-center mb-2'>
              <input
                style={{ display: 'none' }}
                ref={ inputDniRef }
                onChange={ handleDniImgChange }
                type='file'
                accept='image/*'
              />
              {dniImg ? (
                <img 
                  width='100%' 
                  height='100%' 
                  // src={ URL.createObjectURL(dniImg) }
                  src={ dniImg } 
                  alt='dni'
                />
              ) : 'No hay imagen'}
            </ImageContainer>
            <LoadButton 
              type='button'
              className='btn'
              onClick={ handleDniImgClick }
              >Cargar imagen (DNI)
            </LoadButton>
          </div>
          {dniImgError && (
            <FieldError>{ dniImgError }</FieldError>
          )}
        </div>

        {loading ? (
          <Loading />
        ) : (
          <div className='d-flex'>
            <CancelButton 
              type='button'
              className='btn btn-md btn-block mt-4 mr-3'
              onClick={ handleCancel }
              >Cancelar
            </CancelButton>
            <SubmitButton 
              type='submit'
              className='btn btn-md btn-block mt-4'
              >Guardar
            </SubmitButton>
          </div>
        )}
      </CardForm>
    </Fragment>
	)
}