//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "CombLoad.h"
#include "String_doubleUnit.h"
#include "alinit.h"
#include "BalkaLoad.h"


//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TCombLoadForm *CombLoadForm;
//---------------------------------------------------------------------------
__fastcall TCombLoadForm::TCombLoadForm(TComponent* Owner)
	: TForm(Owner)
{
   int rc;
   ALLOCMAT_(CombStr, 1, 1);
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::FormShow(TObject *Sender)
{
	   int i, j;
	   AnsiString ind;

	   StringGrid_Combin->ColCount = n_beam + 1;
	   StringGrid_Combin->RowCount = n_beam + 1;
	   StringGrid_Combin->Cells[0][0] = "№ комб.";
	   for (i=1; i<StringGrid_Combin->ColCount; i++) {
		  if (type_zagr[i-1]==zagrCONSTANT)
			ind = " C";
		  if (type_zagr[i-1]==zagrTEMPORAR)
			ind = " L";
		  if (type_zagr[i-1]==zagrTRANSIST)
			ind = " S";
		  StringGrid_Combin->Cells[i][0] = IntToStr(i) + ind;
	   }
	   //
	   if (!flag_comb) {
	   // подсчет постоянных загружений
		 int n_const = 0;
		 int n_dlit = 0;
		 int n_krat = 0;

		 for (i=0; i<n_beam; i++) {
		   if (type_zagr[i]==zagrCONSTANT)
				n_const++;
		   if (type_zagr[i]==zagrTEMPORAR)
				n_dlit++;
		   if (type_zagr[i]==zagrTRANSIST)
				n_krat++;
		 }
		 int n_dlit_comb = 0;
		 if (n_dlit>0)
		   n_dlit_comb = 1;
		 int n_krat_comb = 0;
		 if (n_krat>0)
		   n_krat_comb = 1;
		 for (i=1; i<=n_dlit; i++) {
		   n_dlit_comb *= i;
		 }
		 for (i=1; i<=n_krat; i++) {
		   n_krat_comb *= i;
		 }
		 StringGrid_Combin->RowCount = 2;
		 for (i=1; i<StringGrid_Combin->RowCount; i++) {
			  StringGrid_Combin->Cells[0][i] = IntToStr(i);
		 }
		 int iv = 0;
		 int it = 0;
		 i=1;
		 for (int j=1; j<StringGrid_Combin->ColCount; j++) {
			  switch (type_zagr[j-1]) {
				  case zagrCONSTANT:
				  StringGrid_Combin->Cells[j][i] = 1.0;
				  break;
				  case zagrTEMPORAR:
				  if (iv == 0) {
					StringGrid_Combin->Cells[j][i] = 1.0;
					iv = 1;
				  }
				  else {
					StringGrid_Combin->Cells[j][i] = 0.95;
				  }
				  break;
				  case zagrTRANSIST:
				  if (it == 0) {
					StringGrid_Combin->Cells[j][i] = 1.0;
					it = 1;
				  }
				  else {
					if (it==1) {
					  StringGrid_Combin->Cells[j][i] = 0.9;
					  it = 2;
					}
					else
					  if (it==2)
						StringGrid_Combin->Cells[j][i] = 0.7;
				  }
				  break;
			  }
		 }
	   }
	   else {
		 StringGrid_Combin->RowCount = n_combin + 1;
		 for (i=1; i<StringGrid_Combin->RowCount; i++) {
			 StringGrid_Combin->Cells[0][i] = IntToStr(i);
			 for (j=1; j<StringGrid_Combin->RowCount; j++)
			   StringGrid_Combin->Cells[j][i] = FloatToStr(Combin[i-1][j-1]);
		 }

	   }
       flag_comb = false;
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::PutZagr(int n_beam0, int *type_zagr0, int n_comb0, double **Combin0, bool flag_comb0 )
{
	n_beam = n_beam0;        // Число загружений
	type_zagr = type_zagr0;  // тип загружения
	flag_comb = flag_comb0;
	if (flag_comb)
	  n_combin = n_comb0;
	Combin = Combin0;
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::GetComb(bool *flag_comb0, int *n_comb0 )
{
	*flag_comb0 = flag_comb;
	*n_comb0 = n_combin;
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::StringGrid_CombinSelectCell(TObject *Sender, int ACol,
		  int ARow, bool &CanSelect)
{
	CombRow = ARow;
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::SpeedButton_AddClick(TObject *Sender)
{
	   int i;
	   StringGrid_Combin->RowCount ++;
	   for (i=1; i<StringGrid_Combin->RowCount; i++) {
		  StringGrid_Combin->Cells[0][i] = IntToStr(i);
	   }
	   i=StringGrid_Combin->RowCount - 1;
	   for (int j=1; j<StringGrid_Combin->ColCount; j++) {
			  if (type_zagr[j-1] == zagrCONSTANT)
				 StringGrid_Combin->Cells[j][i] = 1.0;
	   }


}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::SpeedButtonDeleteClick(TObject *Sender)
{
		int i;
		for (i=CombRow; i<StringGrid_Combin->RowCount-1; i++)
		  StringGrid_Combin->Rows[i] = StringGrid_Combin->Rows[i+1];
		StringGrid_Combin->RowCount--;
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::BitBtn_ApplyClick(TObject *Sender)
{
   int i, j, rc;
   n_combin = StringGrid_Combin->RowCount - 1;          // StringGrid_Combin->Rows[1]->Strings[3]
   FREEMAT_(CombStr);
   ALLOCMAT_(CombStr, n_combin, n_beam);
   AnsiString str;
   for (i=0; i<n_combin; i++) {
	   for (j=0; j<n_beam; j++) {
		  str = StringGrid_Combin->Cells[j+1][i+1];
		  rc = String_double_zero_plus("Ячейка ("+IntToStr(i+1)+","+IntToStr(j+1), str, &(CombStr[i][j]));
		  if (rc>0) {
			n_combin = 0;
			return;         //Combin[1][3]                                                                           // Combin[i][j]
		  }
	   }
   }
   flag_comb = true;
   Close();
   return;

}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::BitBtn1Click(TObject *Sender)
{
  Close();
}
//---------------------------------------------------------------------------
void __fastcall TCombLoadForm::StringGrid_CombinKeyDown(TObject *Sender, WORD &Key,
		  TShiftState Shift)
{
		if (Key == vkV && Shift.Contains(ssCtrl))
			PasteExcelDataFromClipboard(StringGrid_Combin);
}
//---------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
void __fastcall TCombLoadForm::PasteExcelDataFromClipboard(TStringGrid* StringGrid)
{
	TStringList *UPtrBuffLines;
	TStringList *UPtrBuffLine;
//Проверяем буффер на наличие данных с \r\n в конце каждой строки
	if (!Clipboard()->HasFormat(CF_TEXT)){
		MessageDlg(u"Буфер не содержит данных!",
			mtInformation, TMsgDlgButtons() << mbOK, 0);
		return;
	}
//Записываем строки строк буфера в массив по умному указателю строк std::unique_ptr<BuffLines>
	//const auto UPtrBuffLines {std::make_unique<TStringList>()};
	UPtrBuffLines = new TStringList();
	UPtrBuffLine = new TStringList();

	UPtrBuffLines -> Delimiter = '\n';
	UPtrBuffLines -> StrictDelimiter = true;
	UPtrBuffLines -> DelimitedText = Clipboard() -> AsText;
//Определение индексов выбранной стартовой ячейки для вставки StringGrid
	const int SelectedCellCol = StringGrid -> Col;
	const int SelectedCellRow = StringGrid -> Row;
	if (SelectedCellCol==0 || SelectedCellRow==0)
	   return;
	StringGrid->Options >> goEditing;
	String Str0="0";
	String Str;
//Итерация по строкам строк буффера
	for (int I = 0; I < UPtrBuffLines -> Count; I++){
//Записываем строки строки буфера в массив по умному указателю строк std::unique_ptr<BuffLine>
		//const auto UPtrBuffLine {std::make_unique<TStringList>()};
		UPtrBuffLine -> Delimiter = '\t';
		UPtrBuffLine -> StrictDelimiter = true;
		UPtrBuffLine -> DelimitedText = UPtrBuffLines -> Strings [I];

//Итерация по строкам строки буффера
		for (int J = 0; J < UPtrBuffLine -> Count; J++) {
			if (UPtrBuffLine->Strings[J]=="\0") {
			  Str=Str0;
			}
			else
			   Str = UPtrBuffLine -> Strings[J];
			if (Str==u"\r")
			  Str="0";
			wchar_t *cc =Str.LastChar();
			if (*cc==u'\r')
			  *cc = ' ';
			StringGrid -> Cells[J + SelectedCellCol]
							   [I + SelectedCellRow] = Str;
		}
	}
	delete (UPtrBuffLines);
	delete (UPtrBuffLine);
	StringGrid->Options << goEditing;
}

void __fastcall TCombLoadForm::SpeedButtonPasteFromClipboardClick(TObject *Sender)

{
	 PasteExcelDataFromClipboard(StringGrid_Combin);
}
//---------------------------------------------------------------------------

