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

namespace Toast.SmartDownloader.Example
{
    public class ThreadProgressContainer : MonoSingleton<ThreadProgressContainer>
    {
        private Dictionary<int, ThreadProgress> _progressBars = new Dictionary<int, ThreadProgress>();

        private Transform _threadProgressParent;
        public ThreadProgress ThreadProgressTemplate;

        private int _current = 0;

        public int ThreadCount { get { return _progressBars.Count; } set { Invalidate(value); } }

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

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

        private void Invalidate(int newCount)
        {
            if (newCount == _progressBars.Count || newCount <= 0)
                return;

            var count = _progressBars.Count;
            if (newCount > count)
            {
                var createCount = newCount - count;
                for (int i = 0; i < createCount; i++)
                    AddThreadProgress();
            }
            else if (newCount < count)
            {
                var deleteCount = count - newCount;
                for (int i = 0; i < deleteCount; i++)
                    RemoveThreadProgress();
            }
        }

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

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

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

        private void RemoveThreadProgress()
        {
            var index = --_current;
            Destroy(_progressBars[index].gameObject);
            _progressBars.Remove(index);
        }
    }
}