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

#include <vcl.h>
#include <Vcl.Clipbrd.hpp>
#pragma hdrstop

#include "TablZagr.h"
#include "String_doubleUnit.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TTablZagrForm *TablZagrForm;
//---------------------------------------------------------------------------
__fastcall TTablZagrForm::TTablZagrForm(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TTablZagrForm::PutLoadRegion(double Length_beam, int k_zagr, int *type_zagr, int length_q, BeamRegion *Aq, int length_N, BeamRegion *AN,
									int length_loads, Load *Aloads, TObject *Sender) {

	Label_zagr->Caption = "Заружение "+IntToStr(k_zagr+1);
	ComboBox_type_zagr->ItemIndex = type_zagr[k_zagr];
	length_q0 = length_q;
	Aq0 = Aq;
	length_q0 = length_q;
	Aq0 = Aq;
	length_N0 = length_N;
	AN0 = AN;
	length_loads0 = length_loads;
	Aloads0 = Aloads;
	type_zagr0 = type_zagr[k_zagr];
	Length_beam0 = Length_beam;

	int i;
	 StringGrid_q->RowCount = 1 + length_q0;
	 StringGrid_q->ColCount = 5;
	 StringGrid_q->Rows[0]->CommaText = "№, \"X1, м\", \"X2, м\", \"q_1, кН/м\", \"q_2, кН/м\"";
	 for (i=0; i<length_q0; i++) {
	   StringGrid_q->Cells[0][i+1] = i+1;
	   StringGrid_q->Cells[1][i+1] = FloatToStr(Aq0[i].X0);
	   StringGrid_q->Cells[2][i+1] = FloatToStr(Aq0[i].X0 + Aq0[i].Len);
	   StringGrid_q->Cells[3][i+1] = FloatToStr(Aq0[i].begValue);
	   StringGrid_q->Cells[4][i+1] = FloatToStr(Aq0[i].endValue);
	 }
	 if (length_q0>0) {
		 PageControl_zagr->ActivePage = TabSheet_q;
	 }
	 StringGrid_N->RowCount = 1 + length_N0;
	 StringGrid_N->ColCount = 5;
	 StringGrid_N->Rows[0]->CommaText = "№, \"X1, м\", \"X2, м\", \"n_1, кН/м\", \"n_2, кН/м\"";
	 for (i=0; i<length_N0; i++) {
	   StringGrid_N->Cells[0][i+1] = i+1;
	   StringGrid_N->Cells[1][i+1] = FloatToStr(AN0[i].X0);
	   StringGrid_N->Cells[2][i+1] = FloatToStr(AN0[i].X0 + AN0[i].Len);
	   StringGrid_N->Cells[3][i+1] = FloatToStr(AN0[i].begValue);
	   StringGrid_N->Cells[4][i+1] = FloatToStr(AN0[i].endValue);
	 }
	 if (length_N0>0) {
		 PageControl_zagr->ActivePage = TabSheet_N;
	 }
	 StringGrid_Loads->RowCount = 1 + length_loads0;
	 StringGrid_Loads->ColCount = 5;
	 StringGrid_Loads->Rows[0]->CommaText = "№, \"X, м\", \"Q, кН\", \"N, кН\", \"My, кН*м\"";
	 for (i=0; i<length_loads0; i++) {
	   StringGrid_Loads->Cells[0][i+1] = i+1;
	   StringGrid_Loads->Cells[1][i+1] = FloatToStr(Aloads0[i].X);
	   StringGrid_Loads->Cells[2][i+1] = FloatToStr(Aloads0[i].v);
	   StringGrid_Loads->Cells[3][i+1] = FloatToStr(Aloads0[i].u);
	   StringGrid_Loads->Cells[4][i+1] = FloatToStr(Aloads0[i].c);
	 }
	 if (length_loads0>0) {
		 PageControl_zagr->ActivePage = TabSheet_loads;
	 }
	 Edit_gamma_f->Text = FloatToStr(Koeff_gamma_f);
	 Edit_koef_low->Text = FloatToStr(Koeff_low);
}
//-----------------------------------------------------------
void __fastcall TTablZagrForm::BitBtnCancelClick(TObject *Sender)
{
  Close();

}
//---------------------------------------------------------------------------
void __fastcall TTablZagrForm::BitBtn_ApplyClick(TObject *Sender)
{
	 int i, rc;
	 double x0, x1, x2, p1, p2, Q_, N_, My;

	 type_zagr0 = ComboBox_type_zagr->ItemIndex;
	 length_q0 = StringGrid_q->RowCount - 1;
	 x0 = 0;
	 for (i=0; i<length_q0; i++) {
		  rc = String_double_zero_plus(StringGrid_q->Cells[1][0], StringGrid_q->Cells[1][i+1], &x1);
		  if (rc>0) return;
		  if (x1 < x0) {
			rc = Application->MessageBox(("Координата начала участка X1 ="+FloatToStr(x1)+" не должна быть меньше координаты конца предыдущего участка "+
										  FloatToStr(x0)).c_str(),
						  L" ", MB_OK | MB_ICONERROR);
			return;

		  }
		  rc = String_double_zero_plus(StringGrid_q->Cells[2][0], StringGrid_q->Cells[2][i+1], &x2);
		  if (rc>0) return;
		  if (x2 <= x1) {
			rc = Application->MessageBox(("Координата конца участка X2 ="+FloatToStr(x2)+" должна быть больше координаты начала участка "+
										  FloatToStr(x1)).c_str(),
						  L" ", MB_OK | MB_ICONERROR);
			return;

		  }
		  if (x2 > Length_beam0) {
			rc = Application->MessageBox(("Координата конца участка X2 ="+FloatToStr(x2)+" не должна быть больше длины балки "+
										  FloatToStr(Length_beam0)).c_str(),
						  L" ", MB_OK | MB_ICONERROR);
			return;

		  }
		  rc = String_double(StringGrid_q->Cells[3][0], StringGrid_q->Cells[3][i+1], &p1);
		  if (rc>0) return;
		  rc = String_double(StringGrid_q->Cells[4][0], StringGrid_q->Cells[4][i+1], &p2);
		  if (rc>0) return;
		  x0 = x2;

	   Aq0[i].X0 = x1;
	   Aq0[i].Len = x2 - x1;
	   Aq0[i].begValue = p1;
	   Aq0[i].endValue = p2;
	 }
	 // Распределенная нагрузка N
	 length_N0 = StringGrid_N->RowCount - 1;
	 x0 = 0;
	 for (i=0; i<length_N0; i++) {
		  rc = String_double_zero_plus(StringGrid_N->Cells[1][0], StringGrid_N->Cells[1][i+1], &x1);
		  if (rc>0) return;
		  if (x1 < x0) {
			rc = Application->MessageBox(("Координата начала участка X1 ="+FloatToStr(x1)+" не должна быть меньше координаты конца предыдущего участка "+
										  FloatToStr(x0)).c_str(),
						  L" ", MB_OK | MB_ICONERROR);
			return;

		  }
		  rc = String_double_zero_plus(StringGrid_N->Cells[2][0], StringGrid_N->Cells[2][i+1], &x2);
		  if (rc>0) return;
		  if (x2 > Length_beam0) {
			rc = Application->MessageBox(("Координата конца участка X2 ="+FloatToStr(x1)+" не должна быть больше длины балки "+
										  FloatToStr(Length_beam0)).c_str(),
						  L" ", MB_OK | MB_ICONERROR);
			return;

		  }
		  rc = String_double(StringGrid_N->Cells[3][0], StringGrid_N->Cells[3][i+1], &p1);
		  if (rc>0) return;
		  rc = String_double(StringGrid_N->Cells[4][0], StringGrid_N->Cells[4][i+1], &p2);
		  if (rc>0) return;
		  x0 = x2;

	   AN0[i].X0 = x1;
	   AN0[i].Len = x2 - x1;
	   AN0[i].begValue = p1;
	   AN0[i].endValue = p2;
	 }
	 length_loads0 = StringGrid_Loads->RowCount - 1;
	 x0 = 0;
	 for (i=0; i<length_loads0; i++) {
		  rc = String_double_zero_plus(StringGrid_Loads->Cells[1][0], StringGrid_Loads->Cells[1][i+1], &x1);
		  if (x1 > Length_beam0) {
			rc = Application->MessageBox(("Координата приложения нагрузки X ="+FloatToStr(x1)+" не должна быть больше длины балки "+
										  FloatToStr(Length_beam0)).c_str(),
						  L" ", MB_OK | MB_ICONERROR);
			return;

		  }
		  rc = String_double(StringGrid_Loads->Cells[2][0], StringGrid_Loads->Cells[2][i+1], &Q_);
		  if (rc>0) return;
		  rc = String_double(StringGrid_Loads->Cells[3][0], StringGrid_Loads->Cells[3][i+1], &N_);
		  if (rc>0) return;
		  rc = String_double(StringGrid_Loads->Cells[4][0], StringGrid_Loads->Cells[4][i+1], &My);
		  if (rc>0) return;

	   Aloads0[i].X = x1;
	   Aloads0[i].v = Q_;
	   Aloads0[i].u = N_;
	   Aloads0[i].c = My;
	 }
	 rc = String_double_plus(Label_gamma_f->Caption, Edit_gamma_f->Text, &(Koeff_gamma_f));
	 if (rc>0) return;
	 // Установить понижающий коэфф.
	 rc = String_double_plus_low(Label_koef_low->Caption, Edit_koef_low->Text, 1.0, &(Koeff_low));
	 if (rc>0) return;
	 Close();
}
//---------------------------------------------------------------------------

void __fastcall TTablZagrForm::SpeedButton_AddClick(TObject *Sender)
{
	 //
	 if (PageControl_zagr->ActivePage == TabSheet_N) {
		StringGrid_N->RowCount++;
		StringGrid_N->Rows[StringGrid_N->RowCount-1]->CommaText= IntToStr(StringGrid_N->RowCount-1)+",0, 0,0,0";
		StringGrid_N->Row = 1;
	 }
	 if (PageControl_zagr->ActivePage == TabSheet_q) {
		StringGrid_q->RowCount++;
		StringGrid_q->Rows[StringGrid_q->RowCount-1]->CommaText= IntToStr(StringGrid_q->RowCount-1)+",0, 0,0,0";
		StringGrid_q->Row = 1;
	 }
	 if (PageControl_zagr->ActivePage == TabSheet_loads) {
		StringGrid_Loads->RowCount++;
		StringGrid_Loads->Rows[StringGrid_Loads->RowCount-1]->CommaText= IntToStr(StringGrid_Loads->RowCount-1)+",0, 0,0,0";
		StringGrid_Loads->Row = 1;
	 }
	 //
}
//---------------------------------------------------------------------------

void __fastcall TTablZagrForm::SpeedButtonDeleteClick(TObject *Sender)
{
	 int i;
	 if (PageControl_zagr->ActivePage == TabSheet_N && NRow_N>0) {
		for (i=NRow_N; i<StringGrid_N->RowCount-1; i++)
		  StringGrid_N->Rows[i] = StringGrid_N->Rows[i+1];
		StringGrid_N->RowCount--;
	 }
	 if (PageControl_zagr->ActivePage == TabSheet_q && NRow_q>0) {
		for (i=NRow_q; i<StringGrid_q->RowCount-1; i++)
		  StringGrid_q->Rows[i] = StringGrid_q->Rows[i+1];
		StringGrid_q->RowCount--;
	 }
	 if (PageControl_zagr->ActivePage == TabSheet_loads && NRow_Load>0) {
		for (i=NRow_Load; i<StringGrid_Loads->RowCount-1; i++)
		  StringGrid_Loads->Rows[i] = StringGrid_Loads->Rows[i+1];
		StringGrid_Loads->RowCount--;
	 }
}
//---------------------------------------------------------------------------

void __fastcall TTablZagrForm::StringGrid_qSelectCell(TObject *Sender, int ACol, int ARow,
          bool &CanSelect)
{
   NRow_q = ARow;
}
//---------------------------------------------------------------------------
void __fastcall TTablZagrForm::StringGrid_NSelectCell(TObject *Sender, int ACol, int ARow,
          bool &CanSelect)
{
  NRow_N= ARow;
}
//---------------------------------------------------------------------------

void __fastcall TTablZagrForm::StringGrid_LoadsSelectCell(TObject *Sender, int ACol,
          int ARow, bool &CanSelect)
{
	NRow_Load = ARow;

}
//---------------------------------------------------------------------------

void __fastcall TTablZagrForm::FormShow(TObject *Sender)
{
  	  NRow_Load = 0;
	  NRow_q = 0;
	  NRow_N = 0;

}
//---------------------------------------------------------------------------

void __fastcall TTablZagrForm::StringGrid_LoadsFixedCellClick(TObject *Sender, int ACol,
          int ARow)
{
	NRow_Load = ARow;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void __fastcall TTablZagrForm::StringGrid_LoadsKeyDown(TObject *Sender, WORD &Key,
		  TShiftState Shift)
{
		if (Key == vkV)
			StringGridCurrent = static_cast<TStringGrid*>(Sender);
		if (Key == vkV && Shift.Contains(ssCtrl))
			PasteExcelDataFromClipboard(static_cast<TStringGrid*>(Sender));

}
//-------------------------------------------------------------------------------------
void __fastcall TTablZagrForm::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();          // UPtrBuffLine->Strings[2]

	UPtrBuffLines -> Delimiter = '\n';
	UPtrBuffLines -> StrictDelimiter = true;
	UPtrBuffLines -> DelimitedText = Clipboard() -> AsText;
//Определение индексов выбранной стартовой ячейки для вставки StringGrid
	const int SelectedCellCol = StringGrid -> Col;
	const int SelectedCellRow = StringGrid -> Row;
	if (SelectedCellRow==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;
	//StringGrid->Options << goAlwaysShowEditor;

}

void __fastcall TTablZagrForm::SpeedButtonPasteFromClipboardClick(TObject *Sender)

{
	 if (PageControl_zagr->ActivePage == TabSheet_N) {
		StringGridCurrent = StringGrid_N;
	 }
	 if (PageControl_zagr->ActivePage == TabSheet_q) {
		StringGridCurrent = StringGrid_q;
	 }
	 if (PageControl_zagr->ActivePage == TabSheet_loads) {
		StringGridCurrent = StringGrid_Loads;
	 }
	 PasteExcelDataFromClipboard(StringGridCurrent);

}
//---------------------------------------------------------------------------

