extends Control
@onready var grid_container: GridContainer = $GridContainer
@onready var http_request: HTTPRequest = HTTPRequest.new()
static var button_template: PackedScene =
preload("res://Scenes/CategoryItemButtonTemplate.tscn") # Update with your button
template path
#static var button: Button = button_template.instantiate() as Button
var api_url: String = "https://coloringbook.yourartmate.com/api/category.php" #
Replace with your API endpoint
var category_button_map: Dictionary = {} # Mapping of category_id to buttons for
caching
# Cache variables
#static var cache_path: String = ""
static var button_reference: Button
static var temp_path:String =""
func _ready() -> void:
# Add HTTPRequest node to the scene and connect its signal
add_child(http_request)
http_request.request_completed.connect(_on_request_completed)
# Fetch categories on ready
fetch_categories()
# Fetch categories from the API
func fetch_categories() -> void:
var error = http_request.request(api_url)
if error != OK:
push_error("Failed to create HTTP request. Error code: %d" % error)
# Handle HTTPRequest completion signal
func _on_request_completed(result: int, response_code: int, headers:
PackedStringArray, body: PackedByteArray) -> void:
if result == HTTPRequest.RESULT_SUCCESS and response_code == 200:
var json_parser = JSON.new()
var parse_result = json_parser.parse(body.get_string_from_utf8())
if parse_result == OK:
var json_data: Array = json_parser.data.get("data", {}).get("category",
[])
print(json_data.size())
populate_grid(json_data)
else:
print("JSON parsing error: %s" % json_parser.error_string)
else:
print("Request failed. Result: %d, Response code: %d" % [result,
response_code])
# Populate the GridContainer with category buttons
func populate_grid(categories: Array) -> void:
# Clear any previous buttons in the grid
for child in grid_container.get_children():
child.queue_free()
# Iterate over each category and create buttons
for category in categories:
print("The categories:",category)
var button: Button = button_template.instantiate() as Button
var category_id: int = category.get("category_id", -1)
var name=category.get("name", "Unknown")
var texture=""
button.text = category.get("name", "Unknown")
# Map category_id to the button for later use
#category_button_map[category_id] = button
# Load or download the icon
var image_url: String = category.get("image", "")
category_button_map[category_id] =
{"button":button,"name":name,"image":image_url}
var full_image_url: String = "http://coloringbook.yourartmate.com/uploads/"
+ image_url
var cache_path: String = get_cache_path(image_url)
print("The cace:",cache_path)
#self.cache_path=cache_path
if file_exists(cache_path):
button.icon = load_cached_image(cache_path,"")
grid_container.add_child(button)
else:
download_image(full_image_url, cache_path, category_id)
func get_cache_path(image_url: String) -> String:
var filename = image_url.split("/")[image_url.split("/").size() - 1]
return "user://cache/" + filename
# Check if a file exists
func file_exists(path: String) -> bool:
return FileAccess.file_exists(path)
# Store metadata for HTTPRequest instances
var request_metadata = {}
func download_image(url: String, cache_path: String, category_id: int) -> void:
var image_request = HTTPRequest.new()
add_child(image_request)
# Store metadata in a dictionary
request_metadata[image_request] = {"cache_path": cache_path, "category_id":
category_id}
# Use Callable to pass extra arguments
image_request.request_completed.connect(_on_image_downloaded.bind(image_request))
image_request.request(url)
func _on_image_downloaded(result: int, response_code: int, headers:
PackedStringArray, body: PackedByteArray, image_request: HTTPRequest) -> void:
# Retrieve metadata from the dictionary using the image_request instance
var metadata = request_metadata.get(image_request, null)
if metadata:
var cache_path = metadata["cache_path"]
var category_id = metadata["category_id"]
print("Check:", cache_path, category_id)
if result == HTTPRequest.RESULT_SUCCESS and response_code == 200:
# Ensure the directory exists
var dir_access: DirAccess = DirAccess.open("user://")
var dir: String = cache_path.get_base_dir()
if dir_access and not dir_access.dir_exists(dir):
dir_access.make_dir_recursive(dir)
# Save the image to cache
var file: FileAccess = FileAccess.open(cache_path, FileAccess.WRITE)
if file:
file.store_buffer(body)
file.close()
var content_type: String = ""
for header in headers:
print("Header: %s" % header) # Log each header for debugging
if header.strip_edges().to_lower().begins_with("content-type:"):
content_type = header.substr(13, header.length() -
13).strip_edges()
break
# Log the detected content type
if content_type == "":
print("Error: Content-Type header not found.")
return
print("Content-Type: %s" % content_type)
# Handle image based on its content type
if content_type != "image/png" and content_type != "image/jpeg":
print("Error: Unsupported content type: %s" % content_type)
return
if body.size() == 0:
print("Error: Received an empty image body.")
return
# Load the image into a texture
var texture = load_cached_image(cache_path, content_type)
if texture:
var button_reference = category_button_map.get(category_id)
["button"]
if button_reference:
button_reference.icon = texture
grid_container.add_child(button_reference)
else:
print("Image download failed. Result: %d, Response code: %d" %
[result, response_code])
# Cleanup
image_request.queue_free()
request_metadata.erase(image_request) # Remove the metadata after
processing the request
func load_cached_image(path: String, content_type: String) -> Texture2D:
if not file_exists(path):
print("File does not exist:", path)
return null
var image: Image = Image.new()
# Load the image depending on the content type
var load_result = OK
if content_type == "image/png":
var file: FileAccess = FileAccess.open(path, FileAccess.READ)
var body = file.get_buffer(file.get_length())
file.close()
load_result = image.load_png_from_buffer(body)
elif content_type == "image/jpeg":
var file: FileAccess = FileAccess.open(path, FileAccess.READ)
var body = file.get_buffer(file.get_length())
file.close()
load_result = image.load_jpg_from_buffer(body)
else:
# Fallback to loading the image directly
load_result = image.load(path)
if load_result != OK:
print("Failed to load image:", path)
return null
# Create and return a texture from the image
var texture: ImageTexture = ImageTexture.create_from_image(image)
return texture