package org.example.handler;

import com.nhn.gameanvil.common.GameAnvilController;
import com.nhn.gameanvil.game.GameRoomMapping;
import com.nhn.gameanvil.game.IRoomDispatchContext;
import com.nhn.gameanvil.packet.Packet;
import org.example.game.BasicRoom;
import protocol.Puzzle;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@GameAnvilController
public class ScatterPuzzleHandler {
    private static final int mapSize = 400;

    private static class Point {
        public int x;
        public int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    @GameRoomMapping(value = Puzzle.ScatterPuzzle.class, loadClass =  BasicRoom.class)
    public void execute(IRoomDispatchContext ctx, Puzzle.ScatterPuzzle request) {
        BasicRoom room = ctx.getRoom();
        room.puzzlePositions = new HashMap<>();
        List<ScatterPuzzleHandler.Point> random = IntStream.rangeClosed(-4, 4).boxed()
                .map(i -> new Point(i * mapSize / 4, i % 2 == 0 ? mapSize : -mapSize))
                .collect(Collectors.toList());
        random = Stream.concat(random.stream(), random.stream().map(p -> new Point(p.y, p.x))).collect(Collectors.toList());
        Collections.shuffle(random);

        for (int i = 0; i < 16; i++) {
            ScatterPuzzleHandler.Point point = random.get(i);
            int x = 1300 + point.x;
            int y = 550 + point.y;

            Puzzle.PuzzlePosition puzzlePosition = Puzzle.PuzzlePosition.newBuilder().setIndex(i).setPositionX(x).setPositionY(y).build();
            room.puzzlePositions.put(i, puzzlePosition);
            room.broadcast(Packet.makePacket(puzzlePosition));
        }
    }
}
