using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;

using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component;
using Microsoft.BizTalk.Component.Interop;
namespace TM.TransSmart.PipelineComponents
{
    [ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
    [ComponentCategory(CategoryTypes.CATID_DisassemblingParser)]
    [ComponentCategory(CategoryTypes.CATID_Streamer)]
    [Guid("B082AD3E-C313-4569-941E-AE527A7AFD6B")]
    public class CPL_Debatch : IBaseComponent, IDisassemblerComponent, IComponentUI, IPersistPropertyBag
    {

        private string docType = "";

        private const string XmlNormNamespaceURI = "http://schemas.microsoft.com/BizTalk/2003/xmlnorm-properties";
        private const string DocumentSpecNamePropertyName = "DocumentSpecName";

        private Queue<string> messages = new Queue<string>();
        private IBaseMessageContext msgContext = null;
        #region IBaseComponent Members

        public string Description
        {
            get { return "Streaming TransSmart Debatch Disassembler Component"; }
        }

        public string Name
        {
            get { return "TransSmart Debatch Disassembler"; }
        }

        public string Version
        {
            get { return "1.0"; }
        }

        #endregion

        #region IDisassemblerComponent Members

        public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (pInMsg == null) return;
            if (pInMsg.PartCount == 0) return;

            msgContext = PipelineUtil.CloneMessageContext(pInMsg.Context);
            Stream s2 = pInMsg.BodyPart.Data;

            // reset to begin of stream;
            s2.Seek(0, SeekOrigin.Begin);

            StreamReader history = new StreamReader(s2);
            String content = "";
            content = history.ReadToEnd();

            string replace1 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tbox=\"http://connect1.transwise.eu/TboxService/\"><SOAP-ENV:Header xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"/><soap:Body><tbox:carrierBooking>";
            string replaceWith1 = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><tbox:carrierBooking xmlns:tbox=\"http://TM.TransSmart.Shipment\">";

            string replace2 = "</soap:Body></soap:Envelope>";
            string replaceWith2 = "";

            content = content.Replace(replace1, replaceWith1).Replace(replace2, replaceWith2);


            string line = null;
            StringBuilder sb = new StringBuilder(content);
            if (sb.Length != 0)
            {
                messages.Enqueue(sb.ToString());
            }
        }

        public IBaseMessage GetNext(IPipelineContext pContext)
        {

            // Queue is empty ?
            if (messages.Count == 0)
            {
                return null;
            }

            string currentDoc = messages.Dequeue();
            IBaseMessage ret = null;
            IDocumentSpec docSpec = null; 

            docSpec = pContext.GetDocumentSpecByType(@"http://TM.TransSmart.Shipment#carrierBooking");


            IBaseMessage msg = pContext.GetMessageFactory().CreateMessage();

            IBaseMessagePart part = pContext.GetMessageFactory().CreateMessagePart();



            //UnicodeEncoding encoding = new UnicodeEncoding();
            //ASCIIEncoding encoding = new ASCIIEncoding();
            //Byte[] bytes = Encoding.Default.GetBytes(currentDoc);
            Byte[] bytes = Encoding.UTF8.GetBytes(currentDoc);

            MemoryStream ms = new MemoryStream();
            int count = 0;
            while (count < bytes.Length)
            {
                ms.WriteByte(bytes[count]);
                count++;
            }


            ms.Seek(0, SeekOrigin.Begin);

            part.Data = ms;
            msg.AddPart("body", part, true);
            msg.Context = msgContext;


            msg.Context.Write(DocumentSpecNamePropertyName, XmlNormNamespaceURI, docSpec.DocSpecStrongName);

            XmlDasmComp xmldasm = new XmlDasmComp();
            xmldasm.InitNew();
            if (xmldasm.Probe(pContext, msg))
            {
                xmldasm.Disassemble(pContext, msg);
                ret = xmldasm.GetNext(pContext);
            }

            return ret;
        }

        #endregion

        #region IComponentUI Members

        public IntPtr Icon
        {
            get { return IntPtr.Zero; }
        }

        public IEnumerator Validate(object projectSystem)
        {
            return new List<string>().GetEnumerator();


        }

        #endregion

        #region IPersistPropertyBag Members

        public void GetClassID(out Guid classID)
        {
            // Is the Same as GUID on Class level.
            classID = new Guid("B082AD3E-C313-4569-941E-AE527A7AFD6B");

        }

        public void InitNew()
        {
            // Called after "New" of component
        }

        public void Load(IPropertyBag propertyBag, int errorLog)
        {

        }

        public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
        {

        }


        #endregion
    }
}
