// Export Serienbriefsteuerdatei
// nachbearbeiteter Code
// s.a. 2024-08-16
using craftsReport.Interfaces;

namespace craftsReport.modules
{
	public class rkdser_xbs : IReportModule
	{
		public IReportHost HostObject { set; get; }

		int Zeile = 0;

		public rkdser_xbs()
		{
		}

		// Serienbriefsteuerung
		public bool Execute()
		{

			HostObject.DefineVariable2("Charset", "C,10,0");
			HostObject.DefineRecord("Dest", "ADRESSSTAMM", 0, 0, HostObject.EvalString(@""));
			HostObject.Set("Charset", @"ANSI", true);

			if (!HostObject.IsVar("mKond"))
				HostObject.DefineVariable2("mKond", "l,4,0");
			if (!HostObject.IsVar("mSel1"))
				HostObject.DefineVariable2("mSel1", "u,15,0");
			if (!HostObject.IsVar("mSel2"))
				HostObject.DefineVariable2("mSel2", "u,15,0");


			SUB_subKopfZeile();
			HostObject.FindRecord("Dest", HostObject.EvalString("$[KeyVon]"));
			while(!HostObject.TestEof("Dest"))
			{
				SUB_DestLoop();
				HostObject.SkipRecord("Dest");
			}

			return true;
		}

		bool SUB_DestLoop()
		{
			HostObject.VariablesPush();


			if (!HostObject.EvalBool("$[mKond] = 0"))
				if (HostObject.EvalBool("$[mKond] <> $[Dest.KONDITION]"))
					return HostObject.VariablesPop();

			//  * ==================================================
			//  * Abfrage der Bedingung Bis-Key
			if (!HostObject.IsEmpty("KeyBis"))
				if (HostObject.CompareString("Dest.DESTDEBNR", ">", HostObject.EvalString(@"$[KeyBis]")))
				{ 
					HostObject.BreakRecord("Dest");
					return HostObject.VariablesPop();
				}

			//  * ==================================================

			if (!HostObject.IsEmpty("mSel1"))
				if (!HostObject.CompareString("Dest.SELECTION1", "=", HostObject.EvalString(@"$[mSel1]")))
					return HostObject.VariablesPop();

			if (!HostObject.IsEmpty("mSel2"))
				if (!HostObject.CompareString("Dest.SELECTION2", "=", HostObject.EvalString(@"$[mSel2]")))
					return HostObject.VariablesPop();

			SUB_subDestZeile();

			return HostObject.VariablesPop();
		}

		bool SUB_subKopfZeile()
		{
			HostObject.VariablesPush();
			HostObject.WriteLine(HostObject.EvalString(@"Zeile;Nr;Anrede;Vorname;Name1;Name2;Branche;Strasse;Plz;Ort;Selection1;Selection2;ZuHaenden;BrAnrede;FaxNummer;"));
			return HostObject.VariablesPop();
		}

		bool SUB_subDestZeile()
		{
			HostObject.VariablesPush();
			HostObject.WriteLine((++Zeile).ToString() + ";" + HostObject.EvalString(
				"$[Dest.DESTDEBNR];$[Dest.ANREDE];$[Dest.VORNAME];$[Dest.Name1];$[Dest.Name2];$[Dest.Branche];" +
				"$[Dest.Strasse];$[Dest.Plz<8];$[Dest.Ort];$[Dest.Selection1];$[Dest.Selection2];$[Dest.zuHaenden];$[Dest.BrAnrede];$[Dest.FaxNummer];"));
			return HostObject.VariablesPop();
		}
	}
}
