/*-------------------------------------------------------------------------
 * 功能描述:BimDocument
 * 作者:xulisong
 * 创建时间: 2019/6/13 11:01:06
 * 版本号:v1.0
 *  -------------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JBIM
{
    /// <summary>
    /// Bim文件类信息
    /// </summary>
    public class BimDocument
    {
        public BimDocument()
        {
            BimObjects = new ReadOnlyCollection<BimObject>(m_InnerObjects = new List<BimObject>());
        }

        private List<BimObject> m_InnerObjects;
        private Dictionary<BimId, BimObject> m_IndexObjects = new Dictionary<BimId, BimObject>();
        /// <summary>
        /// 关联所有对象
        /// </summary>
        public ReadOnlyCollection<BimObject> BimObjects { get; private set; }

        /// <summary>
        /// 当前索引信息
        /// </summary>
        private long CurrentIndex { get; set; } = 10000;
        internal BimId GenerateId()
        {
            return new BimId((++CurrentIndex).ToString());
        }

        public BimObject NewObject(BimObject originObject)
        {
            if (originObject.Id != null)
            {
                return originObject;
            }
            originObject.Id = GenerateId();
            AddObject(originObject);
            return originObject;
        }
        /// <summary>
        /// 增加预定义对象
        /// </summary>
        /// <param name="originObject"></param>
        /// <returns></returns>
        public bool AddPredefinedObject(BimObject originObject)
        {
            if (originObject.Id == null)
            {
                return false;
            }

            if (m_IndexObjects.TryGetValue(originObject.Id, out BimObject oldObject))
            {
                //移除信息
                if (oldObject != null)
                {
                    m_InnerObjects.Remove(oldObject);
                }               
                m_IndexObjects[originObject.Id] = originObject;
            }
            else
            {
                AddObject(originObject);
            }
            return true;
        }
        private void AddObject(BimObject originObject)
        {
            this.m_InnerObjects.Add(originObject);
            m_IndexObjects[originObject.Id] = originObject;
        }

        public BimObject GetBimObject(BimId id)
        {
            //查询可优化,简单的二分查找
            if (m_IndexObjects.TryGetValue(id, out BimObject result))
            {
                return result;
            }
            return null;
        }
    }
}