import React from 'react';

function Gamenights(props) {

  const DeleteGameNight = (gameId) => {
    if (props.user !== null) {
      let input = {
        game_id: gameId,
      }
  
      const requestOptions = {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${props.user.jwt}`
        },
        body: JSON.stringify(input)
      };
  
      fetch('api/gamenights', requestOptions)
        .then(response => response.json())
        .then(data => {
          if(data.result !== "Ok") {
            props.setFlash({
              type: "Error",
              message: data.message
            });
          }
        })
        .then(() => props.refetchGamenights());
    }
  }  

  let gamenights = props.gamenights.map(g =>
    (
      <li>
        <span>{g.name}</span>
        {(props.user.id === g.owner_id || props.user.role === "Admin") && 
          <button onClick={() =>DeleteGameNight(g.id, g.owner)}>
            x
          </button>
        }
      </li>
    )
  );

  return (
    <ul>
      {gamenights}
    </ul>
  );
}

export default Gamenights
