﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class FoodMenuList : MonoBehaviour
{

    [SerializeField] private GameObject foodItemPrefab;
    [SerializeField] RectTransform foodTypeTitle;
    [SerializeField] RectTransform foodMenuListPanel;
    [SerializeField] Transform foodMenuParent;

    public void ToggleFoodList ()
    {
        bool newState = !foodMenuListPanel.gameObject.activeSelf;
        foodMenuListPanel.gameObject.SetActive(newState);
        if ( newState )
            GenerateList();
        else
            ClearList();
    }

    public void ClearList ()
    {
        for ( int i = 0 ; i < foodMenuParent.childCount ; i++ )
        {
            Destroy(foodMenuParent.GetChild(i).gameObject);
        }
        //generateList(); 
    }

    public void GenerateList ()
    {
        int i = 1;
        foreach ( FoodType ft in Enum.GetValues(typeof(FoodType)) )
        {
            var foodTypes = CreateFoodTypeTitle(ft, i);

            i++;

            foreach ( var food in foodTypes )
            {
                CreateFoodInList(i, food);
                i++;
            }
        }
    }

    private List<Food> CreateFoodTypeTitle (FoodType ft, int i)
    {
        List<Food> foodTypes = FoodMenu.foodMenu.FindAll(f => f.FoodType == ft);
        Transform title = Instantiate(foodTypeTitle, foodMenuParent).transform;
        UpdateChildTextMeshText(title, ft.ToString());
        return foodTypes;
    }

    private void CreateFoodInList (int i, Food food)
    {
        Transform foodItemUI = Instantiate(foodItemPrefab, foodMenuParent).transform;

        UI.UpdateChildTextMeshText(foodItemUI, 0, food.FoodName);
        UI.UpdateChildTextMeshText(foodItemUI, 1, food.Price.ToString() + "$");

        foodItemUI.GetChild(2).GetComponent<Button>().onClick.AddListener(
            () => DeleteFood(food, foodItemUI));
    }

    private void DeleteFood (Food food, Transform UI)
    {
        FoodMenu.RemoveFood(food);
        Destroy(UI.gameObject);
    }

    private void UpdateChildTextMeshText (Transform ttu, string newText)
    {
        UI.UpdateChildTextMeshText(ttu, -1, newText);
    }
}
