using CommonLang;
using CommonLang.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using XmdsCommonServer.XLS.Data;

namespace XmdsCommonServer.XLS
{
	public class XLSBuffConfigLoader : XLSLoader
	{
		private HashMap<int, BuffConfig> BuffDatas = new HashMap<int, BuffConfig>();

		public XLSBuffConfigLoader(string path)
		{
			byte[] data = Resource.LoadData(path);

			if (data == null)
			{
				throw new Exception("Can not read xls file : " + path);
			}

			using (MemoryStream ms = new MemoryStream(data))
			{
				IWorkbook Workbook = null;
				if (path.Contains(".xlsx"))
				{
					Workbook = new XSSFWorkbook(ms);
				}
				else if (path.Contains(".xls"))
				{
					Workbook = new HSSFWorkbook(ms);
				}

				for (int si = 0; si < Workbook.NumberOfSheets; si++)
				{
					ISheet sheet = Workbook.GetSheetAt(si) as ISheet;
					try
					{
						LoadSheet(sheet);
					}
					catch (Exception error)
					{
						throw new Exception(string.Format("XLSBuffConfigLoader 初始化Buff配置表SheetName = {0},Error = {1}",
							sheet.SheetName, error.ToString()));
					}
				}
			}

			log.Info("XLSBuffConfigLoader 初始化Buff配置.");
		}

		private void LoadSheet(ISheet sheet)
		{
			try
			{
				foreach (BuffConfig m in LoadSheet<BuffConfig>(sheet))
				{
					BuffDatas.Add(m.TriggerID, m);
                }
			}
			catch (Exception error)
			{
				throw new Exception(string.Format("XLSRandomMonsterSkillLoader Error : index  = {0} Error = {1}", 0, error.ToString()));
			}

			log.Info(string.Format("loadSheet【{0}】Complete", sheet.SheetName));
		}

        public BuffConfig GetBuffData(int BuffID)
        {
            return this.BuffDatas.Get(BuffID);
        }

		public HashMap<int, BuffConfig> GetAllDatas()
		{
			return this.BuffDatas;
		}

	}
}