extends Node

var data_provider = preload("res://providers/debug_data.gd").new()
var scale_provider = preload("res://providers/debug_scale.gd").new()

var article_infos: Dictionary[String, ArticleInfo] = {}

var cart: Array[CartEntry] = []
var current_entry: CartEntry = null
var cart_total_cents = 0

var scale_grams: int = 120
var tara_grams: int = 20

signal weights_updated
signal cart_updated

func _ready() -> void:
	article_infos = data_provider.load_articles()
	
	cart_updated.connect(_on_cart_updated)
	
	current_entry = CartEntry.new(article_infos['default_0'])
	update_weights()

func _on_product_selected(id):
	current_entry = CartEntry.new(article_infos[id])
	update_weights()

func _on_cart_updated():
	# Make sure all cart entries have the correct list index
	for i in range(len(cart)):
		cart[i].cart_index = i
	
	# Update the total
	cart_total_cents = 0
	for entry in Global.cart:
		cart_total_cents += entry.price_cents
	
func update_weights():
	current_entry.weight_grams = scale_grams - tara_grams
	current_entry.price_cents = current_entry.weight_grams * current_entry.article_info.price_cents_per_gram
	weights_updated.emit()
	
func set_scale(grams):
	scale_grams = int(grams)
	update_weights()

func set_tara(grams):
	tara_grams = int(grams)
	update_weights()

func confirm_entry():
	cart.append(current_entry)
	current_entry = CartEntry.new(current_entry.article_info)
	update_weights()
	cart_updated.emit()
