package com.dne.ems.repository.impl;

import com.dne.ems.model.MapGrid;
import com.dne.ems.repository.MapGridRepository;
import com.dne.ems.service.JsonStorageService;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Repository
@Primary
public class JsonMapGridRepositoryImpl implements MapGridRepository {

    private static final String FILE_NAME = "map_grids.json";
    private final JsonStorageService jsonStorageService;
    private final List<MapGrid> cache = new ArrayList<>();
    private final AtomicLong idCounter = new AtomicLong(0);

    public JsonMapGridRepositoryImpl(JsonStorageService jsonStorageService) {
        this.jsonStorageService = jsonStorageService;
    }

    @PostConstruct
    public void init() {
        List<MapGrid> data = jsonStorageService.readData(FILE_NAME, new TypeReference<>() {});
        synchronized (cache) {
            cache.addAll(data);
            long maxId = data.stream()
                              .mapToLong(MapGrid::getId)
                              .max()
                              .orElse(0L);
            idCounter.set(maxId);
        }
    }

    @Override
    public MapGrid save(MapGrid mapGrid) {
        synchronized (cache) {
            if (mapGrid.getId() == null) {
                mapGrid.setId(idCounter.incrementAndGet());
                cache.add(mapGrid);
            } else {
                cache.removeIf(g -> g.getId().equals(mapGrid.getId()));
                cache.add(mapGrid);
            }
            jsonStorageService.writeData(FILE_NAME, cache);
            return mapGrid;
        }
    }

    @Override
    public List<MapGrid> saveAll(Iterable<MapGrid> mapGrids) {
        synchronized (cache) {
            List<MapGrid> savedGrids = StreamSupport.stream(mapGrids.spliterator(), false)
                .map(this::save)
                .collect(Collectors.toList());
            return savedGrids;
        }
    }

    @Override
    public Optional<MapGrid> findById(Long id) {
        synchronized (cache) {
            return cache.stream().filter(g -> g.getId().equals(id)).findFirst();
        }
    }

    @Override
    public List<MapGrid> findAll() {
        synchronized (cache) {
            return new ArrayList<>(cache);
        }
    }

    @Override
    public long count() {
        synchronized (cache) {
            return cache.size();
        }
    }

    @Override
    public void deleteById(Long id) {
        synchronized (cache) {
            cache.removeIf(g -> g.getId().equals(id));
            jsonStorageService.writeData(FILE_NAME, cache);
        }
    }

    @Override
    public void deleteAll() {
        synchronized (cache) {
            cache.clear();
            jsonStorageService.writeData(FILE_NAME, cache);
        }
    }

    @Override
    public Optional<MapGrid> findByXAndY(int x, int y) {
        synchronized (cache) {
            return cache.stream().filter(g -> g.getX() == x && g.getY() == y).findFirst();
        }
    }

    @Override
    public List<MapGrid> findAllByOrderByYAscXAsc() {
        synchronized (cache) {
            return cache.stream()
                .sorted(Comparator.comparing(MapGrid::getY).thenComparing(MapGrid::getX))
                .collect(Collectors.toList());
        }
    }
} 