using System;
using System.Data;
using System.Text;
using System.Reflection;
using System.Collections.Generic;

using CS;
using SHN;

namespace FilterAPI.ItemExchange
{
    public class TokenLoader
    {
        public List<Token> TokenInfo = new List<Token>();
        public List<TokenItem> TokenItemIDs = new List<TokenItem>();

        public TokenLoader(Authentication Auth)
        {
            MethodInfo CryptoMethod = CSFile.LoadCode(Auth.ConfigValues["SHNCryptoFile"], "SHN.SHNCrypto", Auth.ConfigValues["SHNCryptoName"]);

            SHNFile Tokens = new SHNFile(String.Format("{0}Tokens.shn", Auth.ConfigValues["FilterSHNPath"]), CryptoMethod);

            if (Tokens.Type == SHNType.TextData) { Tokens.SHNEncoding = Encoding.ASCII; }
            else { Tokens.SHNEncoding = Encoding.GetEncoding("ISO-8859-1"); }

            if (Tokens.Type != SHNType.QuestData) { Tokens.Read(); }
            else { Tokens.ReadQuest(); }

            Tokens.DisallowRowChanges();

            foreach (DataRow Row in Tokens.Table.Rows)
            {
                Token NewToken = new Token()
                {
                    TokenID = Convert.ToByte(Row.ItemArray[0]),
                    TokenName = Convert.ToString(Row.ItemArray[1]),
                    TableName = Convert.ToString(Row.ItemArray[2]),
                    IsCharacter = Convert.ToBoolean(Row.ItemArray[3]),
                };

                TokenInfo.Add(NewToken);
            }

            SHNFile TokenItems = new SHNFile(String.Format("{0}TokenItems.shn", Auth.ConfigValues["FilterSHNPath"]), CryptoMethod);

            if (TokenItems.Type == SHNType.TextData) { TokenItems.SHNEncoding = Encoding.ASCII; }
            else { TokenItems.SHNEncoding = Encoding.GetEncoding("ISO-8859-1"); }

            if (TokenItems.Type != SHNType.QuestData) { TokenItems.Read(); }
            else { TokenItems.ReadQuest(); }

            TokenItems.DisallowRowChanges();

            foreach (DataRow Row in TokenItems.Table.Rows)
            {
                TokenItem NewTokenItem = new TokenItem()
                {
                    ItemID = Convert.ToUInt32(Row.ItemArray[0]),
                    IsMainHandle = Convert.ToBoolean(Row.ItemArray[1]),
                    TokenID = Convert.ToByte(Row.ItemArray[2]),
                    TokenWorth = Convert.ToInt32(Row.ItemArray[3]),
                    TokenCost = Convert.ToInt32(Row.ItemArray[4]),
                    IsCharacterCreated = Convert.ToBoolean(Row.ItemArray[5]),
                    HasUpgrade = Convert.ToBoolean(Row.ItemArray[6]),
                    Upgrade = Convert.ToByte(Row.ItemArray[7])
                };

                TokenItemIDs.Add(NewTokenItem);
            }
        }
    }
}
