using System;
using System.Collections.Generic;
using System.Globalization;

namespace FilterAPI.Networking
{
    public class FiestaCrypto
    {
        public Int16 Xor;

        private Byte[] XorTable;

        public FiestaCrypto(Authentication Auth, Int16 TransferXor, Boolean IsClient = true)
        {
            Xor = TransferXor;

            List<Byte> CryptoBytes = new List<Byte>();

            if (IsClient)
            {
                foreach (String CryptoByte in Auth.ConfigValues["ClientCryptoTable"].Split(new String[] { ", " }, StringSplitOptions.None)) { CryptoBytes.Add(Byte.Parse(CryptoByte, NumberStyles.HexNumber)); }
            }
            else
            {
                foreach (String CryptoByte in Auth.ConfigValues["ServerCryptoTable"].Split(new String[] { ", " }, StringSplitOptions.None)) { CryptoBytes.Add(Byte.Parse(CryptoByte, NumberStyles.HexNumber)); }
            }

            XorTable = CryptoBytes.ToArray();
        }

        public FiestaCrypto(Int16 TransferXor, String CryptoTable)
        {
            Xor = TransferXor;

            List<Byte> CryptoBytes = new List<Byte>();

            foreach (String CryptoByte in CryptoTable.Split(new String[] { ", " }, StringSplitOptions.None)) { CryptoBytes.Add(Byte.Parse(CryptoByte, NumberStyles.HexNumber)); }

            XorTable = CryptoBytes.ToArray();
        }

        public void Crypt(Byte[] Buffer, Int32 Start, Int32 Length)
        {
            for (Int32 Counter = 0; Counter < Length; Counter++)
            {
                Buffer[Start + Counter] ^= XorTable[Xor];

                Xor++;

                if (Xor == 499) { Xor = 0; }
            }
        }

        public void Crypt1(Byte[] Buffer, Int32 Start, Int32 Length)
        {
            for (Int32 Counter = 0; Counter < Length; Counter++)
            {
                Buffer[Start + Counter] ^= XorTable[Xor];

                Xor--;

                if (Xor == 499) { Xor = 0; }
            }
        }
    }
}
