# Source files
CORE_SOURCES := \
  asset_manager.c \
  texture_manager.c \
  event.c \
  vector2d.c \
  linked_list.c \
  display.c

# Compiler and flags
CORE_CC = gcc
#CORE_CFLAGS = -std=c17 -pedantic -O3 -fPIC -DASSET_FILENAME=$(ASSET_OUTPUT) # RELEASE
CORE_CFLAGS = -std=c17 --pedantic -O0 -g -fPIC -DASSET_FILENAME=$(BUILD_DIR)/$(ASSET_OUTPUT) \
	-Wall -Wno-missing-braces -Wextra -Wno-missing-field-initializers \
    -Wformat=2 -Wswitch-default -Wswitch-enum -Wcast-align \
    -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 \
    -Wstrict-prototypes -Winline -Wundef -Wnested-externs \
    -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op \
    -Wfloat-equal -Wstrict-aliasing=2 -Wredundant-decls \
    -Wold-style-definition # DEVELOPEMENT

CORE_INCLUDE_DIRS = $(CORE_DIR)/headers
CORE_LDFLAGS = $(shell sdl2-config --cflags --libs) -lSDL2_image $(shell pkg-config --libs liblz4) -ltar

# Deduce objects
CORE_OBJECTS = $(CORE_SOURCES:%.c=$(BUILD_DIR)/$(CORE_DIR)/%.o)

# Current file nb to process
CURRENT_CORE_FILE := 0

# Build core target
build_core: core_setup count_core_build $(BUILD_DIR)/libCore.so core_end

# Core build directories
core_setup:
	@echo "Building libCore.so (1/3)"
	$(Q)mkdir -p $(dir $(CORE_OBJECTS))

# Count nb of files to build
count_core_build:
	$(eval export TOTAL_CORE_FILES := $(shell echo $$(($$(make -n $(CORE_OBJECTS) 2>/dev/null | grep -c "Building") + 1))))

# Link core target
$(BUILD_DIR)/libCore.so: $(CORE_OBJECTS)
	@echo -e "[100%] $(YELLOW)Linking libCore.so$(RESET)"
	$(Q)$(CORE_CC) -shared $(CORE_OBJECTS) -o $@ $(CORE_LDFLAGS)

# Build .o files
$(BUILD_DIR)/$(CORE_DIR)/%.o: $(CORE_DIR)/%.c
	$(eval CURRENT_CORE_FILE := $(shell echo $$(($(CURRENT_CORE_FILE)+1))))
	$(eval PERCENTAGE := $(shell echo $$(($(CURRENT_CORE_FILE)*100/$(TOTAL_CORE_FILES)))))
	@echo -e "[$(PERCENTAGE)%] $(GREEN)Building C object $@$(RESET)"
	$(Q)$(CORE_CC) $(CORE_CFLAGS) $(CORE_INCLUDE_DIRS:%=-I%) -MMD -MP -c $< -o $@

# Print ending message
core_end: $(BUILD_DIR)/libCore.so
	@echo "Built target libCore.so"

# Source files dependencies
-include $(SOURCE_OBJECTS:.o=.d)
