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

#include <vcl.h>
#include<math.hpp>
#include <stdio.h>
#pragma hdrstop
#include "math.h"
#include "Unit1.h"
#include "Unit2.h"
#include "Unit3.h"
#include "Unit4.h"
#include "Unit5.h"
#include "Unit6.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)

#pragma resource "*.dfm"

extern AnsiString uziv_jmeno;
extern AnsiString uziv_spoluprace;
extern AnsiString uziv_skupina;
extern AnsiString uziv_predmet;
extern AnsiString uziv_dalsi;
extern AnsiString zaver;
extern bool zaver_test; 
extern double uroven;
extern double uroven_prijimaci;
extern double utlum;
extern double utlum_celkove;
extern double CD;
extern double PMD;
extern double delka_celkove;
extern int i;
extern int pocet_prvku;
extern void pmdcd_graf(void);
extern void rezerva(void);
extern bool detektor;
AnsiString pripona, wmf, bmp;
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{

}
//---------------------------------------------------------------------------
typedef struct {       //vytvoreni struktury pro ukladani vlaken
        double delka;
        double PMD;
        double CD;
} VLAKNO;

void obr_save (void) {          //fce pro uložení obrazku grafu

        if (Form1->radio_wmf->Checked==1) {     //uzivetel chce ulozit do emf
        Form1->Chart1->Height = Form1->edit_vyska->Text.ToInt()*0.85 ;  //zveteseni,ulozeni a zmenseni grafu útlumu
        Form1->Chart1->Width = Form1->edit_sirka->Text.ToInt()*0.85 ;
        Form1->Chart1->Color = clWhite;         //bile pozadi obrazku
        Form1->Chart1->SaveToMetafile("urovne.wmf");
        Form1->Chart1->Height=220;
        Form1->Chart1->Width=220;
        Form1->Chart1->Color = clBtnFace;       //zpet na sede pozadi

        Form1->Chart2->Height = Form1->edit_vyska->Text.ToInt()*0.85;   //zveteseni,ulozeni a zmenseni grafu CD
        Form1->Chart2->Width = Form1->edit_sirka->Text.ToInt()*0.85;
        Form1->Chart2->Color = clWhite;
        Form1->Chart2->SaveToMetafile("cd.wmf");
        Form1->Chart2->Height=220;
        Form1->Chart2->Width=220;
        Form1->Chart2->Color = clBtnFace;

        Form1->Chart3->Height= Form1->edit_vyska->Text.ToInt()*0.85;    //zveteseni,ulozeni a zmenseni grafu PMD
        Form1->Chart3->Width = Form1->edit_sirka->Text.ToInt()*0.85;
        Form1->Chart3->Color = clWhite;
        Form1->Chart3->SaveToMetafile("pmd.wmf");
        Form1->Chart3->Height=220;
        Form1->Chart3->Width=220;
        Form1->Chart3->Color = clBtnFace;
        }
        else {          //uzivatel chce ulozit do bmp
        Form1->Chart1->Height = Form1->edit_vyska->Text.ToInt() ;           //zveteseni,ulozeni a zmenseni grafu útlumu
        Form1->Chart1->Width = Form1->edit_sirka->Text.ToInt() ;
        Form1->Chart1->Color = clWhite;
        Form1->Chart1->SaveToBitmapFile("urovne.bmp");
        Form1->Chart1->Height=220;
        Form1->Chart1->Width=220;
        Form1->Chart1->Color = clBtnFace;

        Form1->Chart2->Height = Form1->edit_vyska->Text.ToInt();          //zveteseni,ulozeni a zmenseni grafu CD
        Form1->Chart2->Width = Form1->edit_sirka->Text.ToInt();
        Form1->Chart2->Color = clWhite;
        Form1->Chart2->SaveToBitmapFile("cd.bmp");
        Form1->Chart2->Height=220;
        Form1->Chart2->Width=220;
        Form1->Chart2->Color = clBtnFace;

        Form1->Chart3->Height= Form1->edit_vyska->Text.ToInt();            //zveteseni,ulozeni a zmenseni grafu PMD
        Form1->Chart3->Width = Form1->edit_sirka->Text.ToInt();
        Form1->Chart3->Color = clWhite;
        Form1->Chart3->SaveToBitmapFile("pmd.bmp");
        Form1->Chart3->Height=220;
        Form1->Chart3->Width=220;
        Form1->Chart3->Color = clBtnFace;
        }
}

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


void new_trasa (void) {    //fce pro vymazani aktualni trasy
for (int radek=0; radek < Form1->grid->RowCount;radek++) {  //smazani vsech zaznamu v gridu
     Form1->grid->Rows[radek]->Clear();
        }

Form1->grid->RowCount=2;
Form1->Series1->Clear();        //smazani grafu a vsech dalsich potrebnych komponent
Form1->Series2->Clear();
Form1->Series3->Clear();
Form1->Series4->Clear();
Form1->Series5->Clear();
Form4->combo_komp->Clear();
Form4->listbox_komp->Clear();
Form4->valuelist_hodnoty->Strings->Clear() ;
uroven=0.0;                     //nulovani promennych
uroven_prijimaci=0.0;
delka_celkove=0.0;
utlum_celkove= 0.0;
Form4->combo_komp->Text="Zvolte...";
Form4->combo_komp->Items->Add("Zdroj");         //na vyber pouze zdroj
i=1;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{

Form1->Series2->AddXY(0,0,0, clBlue ) ; //graf zacina v 0-0
Form1->Series3->AddXY(0,0,0, clMaroon ) ; //graf zacina v 0-0

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

void __fastcall TForm1::button_zpetClick(TObject *Sender) //obsluha tlacitka zpet
{
if (i<=1)
        {i=1;}
    else {
        if (Form1->grid->Cells[1][i-3]=="Detektor"){  //pokud maže detektor,nastavi detektor na 0
        detektor=0;
        Form1->Series5->Clear();                      // vymazani rezervy vykonu
        }

Form1->grid->Rows[i-2]->Clear() ;       //vymazani posledniho prvku
Form1->grid->Rows[i-3]->Clear() ;
i=i-2;
}

if (Form1->grid->RowCount<=2)
        {new_trasa();}            //v gridu nic neni

        else  {
        Form1->grid->RowCount= grid->RowCount-2;
        Form1->Series1->Delete(Series1->LastValueIndex)  ;   //smaze posledni hodnotu grafu

                if(Form1->Series4->XValues->MaxValue ==0) { // byl smazan detektor
                        Form1->Series4->Clear();            // pak smaze "prubeh" detektoru
                        uroven_prijimaci=0.0;
                }
                else { Form1->Series4->Delete(Series4->LastValueIndex);  //smaze posledni cast usecky urovne detektoru
        }
    delka_celkove=Series1->XValues->Last();     //prirazeni hodnoty celkove delky z posledni hodnoty grafu pro protokol
    utlum_celkove=Series1->YValues->Last();     //prirazeni hodnoty celkovho utlumu z posledni hodnoty grafu pro protokol
    rezerva();                                 //vypocet rezervy
    pmdcd_graf();                               //vypocet  grafu cd a pmd
   
}

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

void __fastcall TForm1::otevritClick(TObject *Sender)           //otevreni html stranky
{
if (OpenDialog->Execute())
        {
        Form1->richedit->Lines->LoadFromFile(OpenDialog->FileName);
        AnsiString name(OpenDialog->FileName);
        AnsiString url(ExtractFilePath(ParamStr(0))+name);      //ziskani cesty
        Form1->web->Navigate(WideString(url))  ;                //zobrazeni ve web komponente
        }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ulozitClick(TObject *Sender)
{

sbutton_saveClick(this);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Konec1Click(TObject *Sender)
{
Close();        
}
//---------------------------------------------------------------------------


void __fastcall TForm1::sbutton_openClick(TObject *Sender)
{
otevritClick(this);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::sbutton_saveClick(TObject *Sender)      //ulozeni protokolu
{
if (SaveDialog->Execute())
  {
Form1->richedit->Lines->SaveToFile(SaveDialog->FileName);
obr_save();             //vyvolani fve pro ulozeni obrazku

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

void __fastcall TForm1::sbutton_newClick(TObject *Sender)
{
novy_protokolClick(this);        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormShow(TObject *Sender) //po startu aplikace
{
Form2->ShowModal();     //zobrazi okno pro zdani uzivatelskych udaju
SetWindowLong(edit_sirka->Handle, GWL_STYLE, GetWindowLong(edit_sirka->Handle, GWL_STYLE) | ES_NUMBER); //osetreni zadani pouze cisel
SetWindowLong(edit_vyska->Handle, GWL_STYLE, GetWindowLong(edit_vyska->Handle, GWL_STYLE) | ES_NUMBER);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Chart2DblClick(TObject *Sender) //fce pro otevreni grafu CD  v novem okne
{
Form3->Series1->Clear();                        //smaze pripadne predchozi grafy ve formulari
Form3->Series2->Clear();
Form3->Series3->Clear();
Form3->Chart1->Assign(Form1->Chart2)  ;         //prirazeni popisu grafu
Form3->Series1->AssignValues(Form1->Series2);   //prirazeni hodnot grafu
Form3->ShowModal();                             //samotne zobrazeni formulare s grafem

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

void __fastcall TForm1::Chart3DblClick(TObject *Sender) //fce pro otevreni grafu PMD  v novem okne
{
Form3->Series1->Clear();                        //smaze pripadne predchozi grafy ve formulari
Form3->Series2->Clear();
Form3->Series3->Clear();
Form3->Chart1->Assign(Form1->Chart3);           //prirazeni popisu grafu
Form3->Series1->AssignValues(Form1->Series3);   //prirazeni hodnot grafu
Form3->ShowModal();                             //samotne zobrazeni formulare s grafem

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

void __fastcall TForm1::Chart1DblClick(TObject *Sender) //fce pro otevreni grafu urovni  v novem okne
{
Form3->Series1->Clear();                        //smaze pripadne predchozi grafy ve formulari
Form3->Series2->Clear();
Form3->Series3->Clear();
Form3->Chart1->Assign(Form1->Chart1)  ;         //prirazeni popisu grafu
Form3->Series1->AssignValues(Form1->Series1);   //prirazeni hodnot grafu
Form3->Series2->AssignValues(Form1->Series4);   //prirazeni hodnot grafu
Form3->Series3->AssignValues(Form1->Series5);   //prirazeni hodnot grafu
Form3->ShowModal();                             //samotne zobrazeni formulare s grafem
        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::button_pridejClick(TObject *Sender)
{
Form4->ShowModal();
}
//---------------------------------------------------------------------------


void __fastcall TForm1::gridDrawCell(TObject *Sender, int ACol, int ARow,       //formatovani bunek v gridu
      TRect &Rect, TGridDrawState State)
{
grid->ColWidths[1]=150;         //sirsi radek pro nazev komponenty
if (grid->Canvas->TextWidth(grid->Cells[ACol][ARow]) !=0) {       //v bunce je text
        if(ACol >=0 && fmod(ARow,2)==0)    {                     //tucne kazdy druhy radek, oramovani a vystredeni textu
                Form1->grid->Canvas->Font->Style = Form1->grid->Canvas->Font->Style << fsBold;
                int odsazeni= grid->DefaultColWidth/2-(grid->Canvas->TextWidth(grid->Cells[ACol][ARow])/2 );
                grid->Canvas->TextRect(Rect,Rect.Left+odsazeni, Rect.Top+3,Form1->grid->Cells[ACol][ARow]);
                grid->Canvas->Pen->Width=0.25;
                grid->Canvas->Pen->Color=clBlack;
                grid->Canvas->MoveTo(Rect.Left, Rect.Top);
                grid->Canvas->LineTo(Rect.Left, Rect.Bottom);
                grid->Canvas->Pen->Width=2;
                grid->Canvas->LineTo(Rect.Right, Rect.Bottom);
                grid->Canvas->Pen->Width=0.25;
                grid->Canvas->LineTo(Rect.Right, Rect.Top);
                grid->Canvas->Pen->Width=2;
                grid->Canvas->LineTo(Rect.Left, Rect.Top);
                }
        else {                //vystředěné netučné řádky
                int odsazeni= grid->DefaultColWidth/2-(grid->Canvas->TextWidth(grid->Cells[ACol][ARow])/3.5 );
                grid->Canvas->TextRect(Rect,Rect.Left+odsazeni, Rect.Top+3,Form1->grid->Cells[ACol][ARow]);
        }

}

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

void __fastcall TForm1::button_vytvorClick(TObject *Sender)
{
Form1->richedit->Lines->Clear();                        //vymazani textu v richedit
if (Form1->radio_bmp->Checked==1) pripona="bmp";        //volba formatu ukladanych souboru
        else pripona = "wmf";

// vložení předvytvořeného HTMl kódu protokolu o měření

Form1->richedit->Lines->Add("<html>\n\
        <head>\n\
        <meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">\n\
        <title>Protokol</title>\n\
        </head>\n\
<body>\n\
<center> <h1>Návrh optické trasy</h1> </center> \n\
<b>Jméno: </b> "+ uziv_jmeno+    "<br> \n\
<b>Spolupracovali: </b> "+uziv_spoluprace+"<br> \n\
<b>Skupina: </b> "+uziv_skupina+"<br>   \n\
<b>Předmět: </b> "+uziv_predmet+"<br>   \n\
<b>Datum: </b> "+DateToStr(Date())+"<br>       \n\
<b>Doplňující údaje: </b> "+uziv_dalsi+"<br><br><br>   \n\
<h2>Seznam prvků trasy</h2> \n\
<table width=\"100%\" align=\"center\" border=\"1\"> \n\
") ;


for (int radky=0; radky< Form1->grid->RowCount;radky++) {      //vytvoreni tabulky prvku na trase
        Form1->richedit->Lines->Add("  <tr align=\"center\" >");
        for (int sloupce=0; sloupce< Form1->grid->ColCount ;sloupce++){
                if (Form1->grid->Cells[sloupce][radky]=="") {}

                else {
                        if (fmod(radky ,2.0)==1.0) {
                                Form1->richedit->Lines->Add("           <td>"+ Form1->grid->Cells[sloupce][radky]+"</td>");
                         }
                         else Form1->richedit->Lines->Add("           <td bordercolor=\"black\"> <b> "+ Form1->grid->Cells[sloupce][radky]+"<b></td>");
                  }
          }
          richedit->Lines->Add("  </tr>");
}
Form1->richedit->Lines->Add("</table> <br>");

if (Form1->Series1->YValues->Count() ==0) {     //vlozeni informaci o parametrech na trase
        Form1->richedit->Lines->Add("Celkový útlum trasy: 0 dB <br> \n\
        Úroveň na konci trasy: 0 dBm <br>\n\
        ");
        }
        else {
         Form1->richedit->Lines->Add("Celkový útlum trasy: "+AnsiString(uroven-Form1->Series1->YValues->Last())+" dB <br> \n\
        Úroveň na konci trasy: "+AnsiString(Form1->Series1->YValues->Last())+" dBm <br>\n\
        ");
}

if (detektor==1) {      //jesltize je na trase detektor, spocita vykonovou rezervu
Form1->richedit->Lines->Add("Rezerva výkonu: "+AnsiString(Form1->Series1->YValues->Last()-Form1->Series4->YValues->Last())+" dBm <br>");
}

if (Form1->Series2->YValues->Count() ==0) {     //jestlize je na trease vlakno, vypocita hodnoty celkove CD a PMD
        Form1->richedit->Lines->Add("Celková chromatická disperze trasy: 0 ps <br> \n\
        Celková polarizační vidová disperze trasy: 0 ps <br><br> \n\
        ");}
        else {
         Form1->richedit->Lines->Add("Celková chromatická disperze trasy: "+AnsiString(Form1->Series2->YValues->Last())+" ps <br> \n\
        Celková polarizační vidová disperze trasy: "+AnsiString(RoundTo(Form1->Series3->YValues->Last(),-4))+" ps <br><br> \n\
        ");
        }
//pridani vysvetlivek
Form1->richedit->Lines->Add("<b>Vysvětlivky:</b><br>\n\
P out - vysílací výkon zdroje [dBm]<br>\n\
P in - min. přijímací úroveň detektoru [dBm]<br>\n\
a - měrný útlum [dB/km]<br>\n\
A - útlum [dB]<br>\n\
D CD - koef. chromat.disperze [ps/(nm*km)]<br>\n\
D PMD - koef. polarizační disperze [ps/km^(1/2)]<br>\n\
") ;

//vlozeni kodu pro zobrazeni obrazku
Form1->richedit->Lines->Add("<h2>Průběh úrovní na trase</h2> \n\
<img src=\"urovne."+pripona+"\" alt=\"Průběh úrovní na trase\" border=\"0\" ><br><br><br>  \n\
<h2>Průběh chromatické disperze</h2> \n\
<img src=\"cd."+pripona+"\" alt=\"Průběh chromatické disperze\" border=\"0\"><br><br><br>  \n\
<h2>Průběh polarizační vidové disperze</h2> \n\
<img src=\"pmd."+pripona+"\" alt=\"Průběh polarizační vidové disperze\" border=\"0\"><br><br><br>  \n\
");

zaver_test=0;

if (SaveDialog->Execute())                                               //vyvolani formulare pro ulozeni
        {
        Form1->richedit->Lines->SaveToFile(SaveDialog->FileName);
        obr_save();                                                     //ulozeni obrazku
        AnsiString name(SaveDialog->FileName);
        AnsiString url(ExtractFilePath(ParamStr(0))+name);
        Form1->web->Navigate(WideString(url))  ;
        }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::button_zobrazClick(TObject *Sender)     //zobrazeni aktualniho protokolu v komponennte web
{
Form1->richedit->Lines->SaveToFile(SaveDialog->FileName+"_tmp");    //ulozeni do pomocneho tmp souboru
AnsiString name(SaveDialog->FileName+"_tmp");
AnsiString url(ExtractFilePath(ParamStr(0))+name);
Form1->web->Navigate(WideString(url))  ;

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


void __fastcall TForm1::novy_protokolClick(TObject *Sender)
{
Form1->richedit->Lines->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::nova_trasaClick(TObject *Sender)
{
new_trasa();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Action1Execute(TObject *Sender)
{
sbutton_saveClick(this);
}
//---------------------------------------------------------------------------


void __fastcall TForm1::Action2Execute(TObject *Sender)
{
novy_protokolClick(this);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Action3Execute(TObject *Sender)
{
otevritClick(this);        
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action) // zobrazeni rozhodovaciho okna pri ukoncovani programu
{
switch(Application->MessageBox("Opravdu chcete ukončit aplikaci","Ukončení",MB_YESNO | MB_ICONQUESTION))
    {
      case ID_YES:
          DeleteFile(SaveDialog->FileName+"_tmp") ;    //smazani docasneho tmp souboru
          Application->Terminate();
          break;

      case ID_NO:
          Abort();
    };

}
//---------------------------------------------------------------------------
void __fastcall TForm1::aboutClick(TObject *Sender)
{
Form5->ShowModal();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::button_zaverClick(TObject *Sender)
{
Form6->Show();
        if (zaver_test==1) {  //jestlize uz azver existuje, v reicheditu smaze minuly zaver
                for (int a = Form6->richedit_zaver->Lines->Count+6; a>0;a--){
                Form1->richedit->Lines->Delete(Form1->richedit->Lines->Count-a);
                }
        }

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



