using System.IO;
using System.Xml.Serialization;

namespace BeWo.Report
{
    public abstract class AbstractBeWoReportObject<T> where T : AbstractBeWoReportObject<T>
    {
        public U CloneToSubclass<U>() where U : T
        {
            using (var sr = new StreamReader(new MemoryStream()))
            {
                new XmlSerializer(typeof(T)).Serialize(sr.BaseStream, this);
                sr.BaseStream.Seek(0, SeekOrigin.Begin);

                string s = sr.ReadToEnd();
                s = s.Replace("<" + typeof(T).Name + " xmlns:xsi", "<" + typeof(U).Name + " xmlns:xsi");

                using (var sw = new StreamWriter(new MemoryStream()))
                {
                    sw.Write(s);
                    sw.Flush();
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);

                    return new XmlSerializer(typeof(U)).Deserialize(sw.BaseStream) as U;
                }
            }
        }
    }
}