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

public class ThreadProgressContainer : MonoSingleton<ThreadProgressContainer>
{
    private Dictionary<int, ThreadProgress> _progressBars = new Dictionary<int, ThreadProgress>();

    private Transform _threadProgressParent;
    public ThreadProgress ThreadProgress;

    private int _current = 0;
    private int _count = 0;

    public int ThreadCount { get { return _count; } set { if(Invalidate(value)) _count = value; } }

    public ThreadProgress this[int index] { get { return _progressBars[index]; } }

    protected override void OnAwake()
    {
        _threadProgressParent = ThreadProgress.transform.parent;
        _progressBars.Add(_current++, ThreadProgress.GetComponentInChildren<ThreadProgress>());
    }

    private bool Invalidate(int newCount)
    {
        if (newCount <= _count)
            return false;

        var createCount = newCount - _count;
        for (int i = 0; i < createCount - 1; i++)
            AddThreadProgress();

        return true;
    }

    private void AddThreadProgress()
    {
        var newObject = Instantiate(ThreadProgress);
        newObject.transform.SetParent(_threadProgressParent);

        var progressBar = newObject.GetComponentInChildren<ThreadProgress>();
        if (progressBar == null)
        {
            Debug.LogError("Failed to found the ProgressBar");
            return;
        }

        _progressBars.Add(_current++, progressBar);
    }
}
