using System;
using craftsReport.Interfaces;

namespace craftsReport.modules
{
	public class rp1022_xbs : IReportModule, IReportModuleEvents
	{
		#region Members and Contructor

		private bool m_IsLastPage = false;
		private int m_ZeileMax;
		private bool m_HideKontierung = false;

		public rp1022_xbs()
		{
		}

		#endregion

		#region IReportModule

		public IReportHost HostObject { set; get; }

		// ER_Kontierung
		public bool Execute()
		{
			if (!HostObject.IsVar("mRepTitle"))
				HostObject.DefineVariable2("mRepTitle", "c,250,0");
			if (HostObject.IsEmpty("mRepTitle"))
				HostObject.Set("mRepTitle", "Rechnungseingang", false);

			// -------------------------------------------------------------------------
			//  Prüfen Sie hier die Übergabe von Filtervariablen
			//  Beispiel
			if (!HostObject.IsVar("FltJahr"))
				HostObject.DefineVariable2("FltJahr", "C,4,0");
			if (!HostObject.IsVar("FltMonat"))
				HostObject.DefineVariable2("FltMonat", "C,2,0");
			if (!HostObject.IsVar("SortExtBnr"))
				HostObject.DefineVariable2("SortExtBnr", "L,1,0");

			if (HostObject.IsVar("mKontieren"))
				m_HideKontierung = !HostObject.EvalBool("$[mKontieren]");

			HostObject.DefineVariable2("mFilterText", "c,250,0");

			// SQL-Abfrage erstellen
			#region SqlQuery (Satznummernabfrage nach recSQLMain)
			// ---------------------------------------------------------------------------------
			System.Text.StringBuilder sbQuery = new System.Text.StringBuilder("SELECT RecId FROM LagerEinKopf WHERE Typ = 'Z'");

			int nJahr  = HostObject.EvalInt("$[FltJahr]");
			int nMonat = HostObject.EvalInt("$[FltMonat]");
			if ((nJahr > 1900) && (nMonat > 0) && (nMonat < 13))
            {
				int nMonat2 = nMonat < 12 ? nMonat + 1 : 1;
				int nJahr2 = nMonat < 12 ? nJahr : nJahr + 1;
				sbQuery.AppendFormat("\r\n AND Datum >= convert(datetime, '{0}-{1}-01', 120)", nJahr, nMonat.ToString().PadLeft(2,'0'));
				sbQuery.AppendFormat("\r\n AND Datum < convert(datetime, '{0}-{1}-01', 120)", nJahr2, nMonat2.ToString().PadLeft(2, '0'));
				HostObject.Set("mFilterText", nMonat.ToString().PadLeft(2, '0') + "/" + nJahr.ToString(), false);
			}
			else if (nJahr > 1900)
            {
				sbQuery.AppendFormat(" AND Datum >= convert(datetime, '{0}-01-01', 120)", nJahr);
				sbQuery.AppendFormat(" AND Datum < convert(datetime, '{0}-01-01', 120)", nJahr + 1);
				HostObject.Set("mFilterText", nJahr.ToString(), false);
			}

			// TODO Projektnummer

			if (HostObject.EvalBool("$[SortExtBnr]"))
				sbQuery.Append("\r\n ORDER BY ExtBelnr");
			else
				sbQuery.Append("\r\n ORDER BY BelNr");

			var recSqlMain = HostObject.DefineSqlRecord("recSQLMain", sbQuery.ToString());
			if (recSqlMain == null)
			{
				HostObject.Confirm("Die SQL-Abfrage ist fehlgeschlagen\r\n\r\n" + sbQuery.ToString());
				return false;
			}
			// HostObject.Confirm(sbQuery.ToString());
			// ---------------------------------------------------------------------------------
			#endregion

			HostObject.LoadAdditionalResources("/r");
			HostObject.PaperDefinition("PaperDefinition");
			m_ZeileMax = HostObject.EvalInt("$[ZlMax]");

			HostObject.DefineVariable2("mBrutto", "N,14,2");
			HostObject.DefineVariable2("mAusgleich", "N,14,2");
			HostObject.DefineRecord("recMAIN", "LAGEREINKOPF", 0, 0, "");

			HostObject.DokumentStart();
			HostObject.SeitenKopf();

			while (!recSqlMain.Eof)
			{
				int recId = HostObject.CastInt(recSqlMain.GetI(1));
				HostObject.SeekRecord("recMain", recId);
				SUB_loopMAIN();
				recSqlMain.GoNext();
			}

			m_IsLastPage = true;
			HostObject.SeitenFuss();
			HostObject.DokumentEnde();

			return true;
		}

		#endregion

		#region IReportModuleEvents

		public void OnAfterPageStart()
		{
			HostObject.ProcessResource("KopfDetail");

			if (HostObject.EvalInt("$[Seite]") == 1)
			{
			}
			else
			{
				HostObject.ProcessResource("Uebertrag");
			}
		}

		public void OnBeforePageClose()
		{
			if (m_IsLastPage)
			{
				if ((m_ZeileMax - 2) > HostObject.EvalInt("$[Zeile]"))
					HostObject.ProcessResource("Sterne");
				HostObject.ProcessResource("FussBericht");
			}
			else
			{
				HostObject.ProcessResource("FussSeite");
			}
		}

		public void OnAfterExecute(string szOutFileName)
		{
		}

		#endregion

		#region Internals

		bool SUB_loopMAIN()
		{
			HostObject.VariablesPush();

			HostObject.DefineVariable2("mJahr", "C,4,0");
			HostObject.DefineVariable2("mHelp", "C,5,0");
			HostObject.DefineVariable2("mMonat", "C,2,0");
			HostObject.DefineVariable2("mcAusgleich", "C,14,0");

			HostObject.Set("mJahr", @"$[recMAIN.Datum>4]", true);
			HostObject.Set("mHelp", @"$[recMAIN.Datum<5]", true);
			HostObject.Set("mMonat", @"$[mHelp>2]", true);

			// Kladdentransaktion ermitteln
			if (String.IsNullOrEmpty(HostObject.EvalString("$[recMAIN.TransNo]")))
				if (HostObject.EvalInt("$[recMAIN.KladLfdNr]") != 0)
				{
					HostObject.DefineRecord("recKladde2", "KladdenZeile", 0, 28, HostObject.EvalString("$[recMAIN.KladCode<20]$[recMAIN.KladLfdNr>8]"));
					HostObject.Set("recMAIN.TransNo", "$[recKladde2.TransNo]" , true);
				}
			HostObject.DefineRecord("recTrnK", "BUCHUNGSZEILEN", 5, 17, HostObject.EvalString(@"$[recMAIN.TransNo<8]P$[recMAIN.KredKto<8]"));
			if (HostObject.EvalBool("($[recTrnK.AusglBtr]) <> (0)"))
				HostObject.Set("mcAusgleich", @"$[recTrnK.AusglBtr]", true);

			int SpaceToCheck = 3;
			var recTrnG = HostObject.DefineRecord("recTrnG", "BUCHUNGSZEILEN", 1, 8, HostObject.EvalString(@"$[recMAIN.TransNo<8]"));
			if (!m_HideKontierung)
			{
				while (!recTrnG.Eof)
				{
					if (Test_RecTrnG()) SpaceToCheck++;
					recTrnG.GoNext();
				}
			}

			HostObject.CheckPageSpace(SpaceToCheck);
			HostObject.ProcessResource("outMAIN");
			HostObject.Set("mBrutto", @"$[mBrutto] + $[recMAIN.SummeBrutt]", true);
			HostObject.Set("mAusgleich", @"$[mAusgleich] + $[recTrnK.AusglBtr]", true);
			if (HostObject.IsEmpty("recMAIN.TransNo"))
			{
				if (!m_HideKontierung)
				{
					HostObject.LineFeed(1);
				}
				return HostObject.VariablesPop();
			}

			//  -----------------------------------------------------------------------------
			if (!m_HideKontierung)
			{
				recTrnG.GoTop();
				while (!recTrnG.Eof)
				{
					if (Test_RecTrnG()) Out_RecTrnG();
					recTrnG.GoNext();
				}
				if ((m_ZeileMax - 2) > HostObject.EvalInt("$[Zeile]"))
				{
					HostObject.LineFeed(1);
				}
			}
			return HostObject.VariablesPop();
		}

		bool Test_RecTrnG()
        {
			if (HostObject.CompareString("recTrnK.Typ", "=", HostObject.EvalString(@"$[recTrnG.Typ]")))
				if (HostObject.CompareString("recTrnK.Konto", "=", HostObject.EvalString(@"$[recTrnG.Konto]")))
					return false;
			if (HostObject.EvalBool("($[recTrnG.Soll]) <> (0)"))
				return true;
			if (HostObject.EvalBool("($[recTrnG.Haben]) = (0)"))
				return true;
			return false;
		}

		bool Out_RecTrnG()
		{
			HostObject.VariablesPush();
			HostObject.DefineVariable2("mcHaben", "C,14,0");
			HostObject.DefineVariable2("mcSoll", "C,14,0");
			HostObject.DefineRecord("recSKto", "KONTENPLAN", 0, 9, HostObject.EvalString(@"$[recTrnG.Typ<1]$[recTrnG.Konto<8]"));

			if (HostObject.EvalBool("($[recTrnG.Soll]) <> (0)"))
				HostObject.Set("mcSoll", @"$[recTrnG.Soll]S", true);
			if (HostObject.EvalBool("($[recTrnG.Haben]) <> (0)"))
				HostObject.Set("mcHaben", @"$[recTrnG.Haben]H", true);

			HostObject.CheckPageSpace(3);
			HostObject.ProcessResource("outloopTrnG");
			return HostObject.VariablesPop();
		}

		#endregion
	}
}
