package be.naaturel.boardmateapi.services;

import be.naaturel.boardmateapi.common.exceptions.ServiceException;
import be.naaturel.boardmateapi.common.models.Game;
import be.naaturel.boardmateapi.common.models.Move;
import be.naaturel.boardmateapi.repository.GameRepo;
import be.naaturel.boardmateapi.repository.dtos.GameDto;
import be.naaturel.boardmateapi.repository.mappings.GameMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Collection;
import java.util.Optional;

@Service
public class GameService {

    private final GameRepo repo;

    @Autowired
    public GameService(GameRepo repo){
        this.repo = repo;
    }

    public void save(Game game){
        GameDto gameDto = GameMapper.toDto(game);
        repo.save(gameDto);
    }

    public Game retrieveGame(String id){
        Optional<GameDto> dtoOpt = repo.findById(id);
        return dtoOpt.map(GameMapper::toModel).orElse(null);
    }

    public String create(Game game){
        GameDto gameDto = GameMapper.toDto(game);
        repo.save(gameDto);
        return gameDto.getId();
    }

    public String addMove(@RequestBody String gameId, @RequestBody String move) throws ServiceException {
        try {
            Game g = retrieveGame(gameId);
            g.addMove(move);
            save(g);
            return g.getId();
        } catch (Exception e) {
            throw new ServiceException(e.getMessage(), e);
        }
    }
}
