Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.7 kB
4
Indexable
Never
"use client";

import React, { useEffect, useState, useContext } from "react";
import { UserContext } from './UsernameProvider';
const myUserId = 1

export default function TimeslotComponent({id,title, usersId}){
  const [show, setShow] = useState(false);
  const [nameState, setNameState] = useState(usersId);

  const userContext = useContext(UserContext)
  const [usernames, setUsernames] = useState()
  useEffect(() => {
    userContext.then(result => setUsernames(result))
  }, [userContext])

  useEffect(() => {
    console.log(nameState)
  }, [nameState])

  return (
    <div className="relative z-1 h-full">
      <div className="absolute right-0 left-0 top-0  p-0.5  bg-zinc-50 m-0.5">
        <div className=" pt-0 p-1 lg:text-sm text-xs font-mono rounded-lg rounded-bl-none rounded-tr-none rounded-tl-none  min-h-full w-full  bg-[#7c4145]" onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)} >
          <div className="lg:flex justify-between">
            <div className="font-white font-semibold capitalize lg:underline underline-offset-4 decoration-pink-500 decoration-2 lg:mt-1">{title}</div>
            {
              (!!nameState.includes(myUserId)) ? <IsFreeButton id={id} setName={setNameState}/> : <IsBusyButton id={id} setName={setNameState}/>
            }
          </div>
          {show && <div className=" capitalize">{nameState.map(userId => <div >{usernames[userId]}</div>)}</div>}
        </div>
      </div>
      <div className="bg-[#3F565F] w-1 ml-0.5 h-full z-0">
      </div>
    </div>
    
  )
}



function IsFreeButton({id, setName}){
  return <button className="bg-green-500  border-transparent text-white font-semibold px-1 lg:mt-1 border rounded hover:border-green-500 hover:bg-transparent hover:text-green-700" onClick={() => {removeMeToTimeslot(id); setName(prevNames => removeName(prevNames))}}>Free</button>
}

function IsBusyButton({id, setName}){
  return <button className="bg-red-500    border-transparent text-white font-semibold px-1 lg:mt-1 border rounded hover:border-red-500   hover:bg-transparent hover:text-red-700" onClick={() => {addMeToTimeslot(id); setName(prevNames => addName(prevNames))}}>Busy</button>
}


function addName(names){
  return [].concat(names, myUserId);
}
function removeName(names){
  return names.filter(name => name != myUserId);
}


async function addMeToTimeslot(id){
  await fetch(`/api/timeslot/user/add?userId=1&groupId=1&timeslotId=${id}`, {method: "PUT",})
}
async function removeMeToTimeslot(id){
  await fetch(`/api/timeslot/user/del?userId=1&groupId=1&timeslotId=${id}`, {method: "DELETE",})
}