/* MSHV HvEditW
 * Copyright 2015 Hrisimir Hristov, LZ2HV
 * (Edited by Harper Innes, VK1TTY - to remove Gendered Language and Replace with Non-Gendered language)  NOTE:May be used under the terms of the GNU General Public License (GPL)
 */
#include "hveditw.h"
#include "../../config_str_exc.h"

#define _CONT_NAME_
#include "../../config_str_con.h"

#include "config_prop_all.h"

#define _BANDS_H_
#include "../../config_band_all.h"

#include "../../config_str_all.h"
//#include <QtGui>

HvEditW::HvEditW(QString name,QString bt_cancel_txt,QString bt_corr_txt,bool indsty,QWidget * parent )
        : QWidget(parent)
{
	s_dist = "";
    s_enum_sec_sta = "";
    s_enum_sec_end = "";
    index_edit = -1;
    next_dupe = -1;
    block_txrst = true;
    block_rxrst = true;
    block_rxsn = true;
    block_call = true;
    block_loc = true;
    block_dupe = false;// ina4e vednaga pokazva dupe
    first_dupe_flag = false;
    first_dupe = -1;

    QLabel *l_e = new QLabel();
    if (indsty) l_e->setText("<h3><font color='#00c800'>"+name);//EDIT QSO
    else l_e->setText("<h3><font color=green>"+name);//EDIT QSO
    //l_e->setFixedWidth(140);

    QLabel *l_d_s = new QLabel();
    l_d_s->setText(tr("Date UTC Start")+":");
    //l_d_s->setFixedWidth(102);//125%
    dte_s = new QDateTimeEdit();
    dte_s->setDisplayFormat("yyyy-MM-dd  hh:mm");
    dte_s->setMinimumWidth(90);

    QLabel *l_d_e = new QLabel();
    l_d_e->setText(tr("End")+":");
    //l_d_e->setFixedWidth(28);//125%
    dte_e = new QDateTimeEdit();
    dte_e->setDisplayFormat("yyyy-MM-dd  hh:mm");
    dte_e->setMinimumWidth(90);

    QLabel *l_m = new QLabel();
    l_m->setText(tr("Mode")+":");
    //l_m->setFixedWidth(35);
    Cb_mode = new QComboBox();
    QStringList lst_m;

    for (int i = 0; i < COUNT_MODE; ++i) lst_m<<ModeStr(pos_mods[i]);//2.67
    //NO DG MODES
    lst_m<<"SSB"<<"CW"<<"FM";

    Cb_mode->addItems(lst_m);
    Cb_mode->setCurrentIndex(0);
    Cb_mode->setFixedWidth(95);//1.81  1.50 85 75
    QLabel *l_ba = new QLabel();
    l_ba->setText(tr("Band")+":");
    //l_ba->setFixedWidth(35);//1.50 38
    Cb_band = new QComboBox();
    QStringList lst_b;
    for (int i = 0; i<COUNT_BANDS; ++i)
        lst_b << lst_bands[i];
    Cb_band->addItems(lst_b);
    Cb_band->setCurrentIndex(0);
    Cb_band->setFixedWidth(105);//1.81   1.50 95

    QHBoxLayout *H_dtm = new QHBoxLayout();
    H_dtm->setContentsMargins ( 1, 1, 1, 1);
    H_dtm->setSpacing(3);
    H_dtm->addWidget(l_d_s);
    //H_dtm->setAlignment(l_d_s,Qt::AlignLeft);
    H_dtm->addWidget(dte_s);
    //H_dtm->setAlignment(dte_s,Qt::AlignLeft);
    //H_dtm->addWidget(de_bdate_s);
    //H_dtm->addWidget(l_c_s);
    //H_dtm->addWidget(te_time_s);
    H_dtm->addWidget(l_d_e);
    H_dtm->addWidget(dte_e);
    //H_dtm->addWidget(de_bdate_e);
    //H_dtm->addWidget(l_c_e);
    //H_dtm->addWidget(te_time_e);
    H_dtm->addWidget(l_m);
    //H_dtm->setAlignment(l_m,Qt::AlignLeft);
    H_dtm->addWidget(Cb_mode);
    //H_dtm->setAlignment(Cb_mode,Qt::AlignLeft);
    H_dtm->addWidget(l_ba);
    //H_dtm->setAlignment(l_ba,Qt::AlignLeft);
    H_dtm->addWidget(Cb_band);

    QSpacerItem *space = new QSpacerItem(1,1,QSizePolicy::Expanding);
    H_dtm->addSpacerItem(space);
    //H_dtm->setAlignment(Cb_band,Qt::AlignLeft);

    le_call = new HvInLe("call", tr("CALLSIGN"),indsty);
    connect(le_call, SIGNAL(EmitSndCheck(QString)), this, SLOT(Check(QString)));
    //le_call->setFixedWidthLine(95);
    //le_call->SetMask(">XXXXXXXXXXXXXXXXXXXXXXXX");
    //connect(le_call, SIGNAL(SndCheck(QString)), this, SLOT(Check(QString)));
    //le_call->SndCheck_s("");// proverka v na4aloto
    le_txrst = new HvInLe("txrst","TXRpt",indsty);
    le_txrst->setMaxLength(3);
    //le_txrst->SetMask("#99");//1.41 stop for OOO in jt65 + sh
    le_txrst->setFixedWidth(92);//125%
    //connect(le_txrst, SIGNAL(SndCheck(QString)), this, SLOT(Check(QString)));
    //le_txsn = new HvInLe("txsn", "TxSn");
    //le_txsn->SetMask("99999");
    //le_txsn->setFixedWidth(55);
    //le_txsn->setReadOnly(true);
    le_rxrst = new HvInLe("rxrst","RXRpt",indsty);
    le_rxrst->setMaxLength(3);
    //le_rxrst->SetMask("#99");//1.41 stop for OOO in jt65 + sh
    le_rxrst->setFixedWidth(92);//125%
    //connect(le_rxrst, SIGNAL(SndCheck(QString)), this, SLOT(Check(QString)));
    //le_rxsn = new HvInLe("rxsn", "RxSn");
    //le_rxsn->SetMask("99999");
    //le_rxsn->setFixedWidth(55);
    //connect(le_rxsn, SIGNAL(SndCheck(QString)), this, SLOT(Check(QString)));
    //le_rxsn->SndCheck_s("");// proverka v na4aloto
    le_loc = new HvInLe("locator", tr("LOCATOR"),indsty);
    le_loc->SetMask(">AA99AA");
    le_loc->setFixedWidth(150);//145 125%
    connect(le_loc, SIGNAL(EmitSndCheck(QString)), this, SLOT(Check(QString)));
    //le_loc->SndCheck_s("");// proverka v na4aloto

    QLabel *l_prop = new QLabel();
    l_prop->setText(tr("Propagation")+":");
    //l_prop->setFixedWidth(34);
    cb_prop = new QComboBox();
    cb_prop->setFixedWidth(160);
    QStringList lst_prop;
    for (int i = 0; i<COUNT_PROP; ++i)
        lst_prop<<s_prop_mod[i];
    cb_prop->addItems(lst_prop);
    cb_prop->setCurrentIndex(0);
    //add_to_log_cb_prop->setFixedWidth(86);
    //""<<AUR<<AUE<<BS<<ECH<<EME<<ES<<FAI<<F2<<INTERNET<<ION<<IRL<<MS<<RPT<<RS<<SAT<<TEP<<TR;

    QLabel *l_comment = new QLabel(tr("COMMENT")+":");
    //l_comment->setFixedWidth(50);
    le_comment = new QLineEdit();
    //le_comment->setFixedWidth(140);

    le_freq = new HvInLe("freq", tr("Frequency In")+" kHz:",indsty);
    QRegExp rx("^[1-9][0-9]*$");//^[2-9][0-9]{6}$ Out of 7 digits 1 is consumed by first position 2-9 and then next 6 digits can be from 0-9
    QValidator *validator = new QRegExpValidator(rx, this);
    le_freq->SetValidatorHv(validator);// only digits
    //le_freq->setMinimumWidth(126);
    le_freq->setFixedWidth(220);
    le_freq->setMaxLength(9);
    QHBoxLayout *H_c = new QHBoxLayout();
    H_c->setContentsMargins ( 1, 1, 1, 1);
    H_c->setSpacing(3);
    H_c->addWidget(le_freq);
    H_c->addWidget(l_prop);
    H_c->addWidget(cb_prop);
    H_c->addWidget(l_comment);
    H_c->setAlignment(l_comment,Qt::AlignRight);
    H_c->addWidget(le_comment);

    QRegExp rx1("^[1-9][0-9]*$");//^[2-9][0-9]{6}$ Out of 7 digits 1 is consumed by first position 2-9 and then next 6 digits can be from 0-9
    QValidator *validator1 = new QRegExpValidator(rx1, this);
    QLabel *l_txsn = new QLabel("TXSn:");
    QLabel *l_rxsn = new QLabel("RXSn:");
    QLabel *l_txex = new QLabel("TXExch:");
    QLabel *l_rxex = new QLabel("RXExch:");
    le_txsn = new QLineEdit();
    le_txsn->setValidator(validator1);
    le_rxsn = new QLineEdit();
    le_rxsn->setValidator(validator1);
    connect(le_rxsn, SIGNAL(textChanged(QString)), this, SLOT(ExchangeChanged(QString)));
    le_txex = new HvLeWithSpace();
    le_rxex = new HvLeWithSpace();
    connect(le_txex, SIGNAL(textChanged(QString)), this, SLOT(ExchangeChanged(QString)));
    connect(le_rxex, SIGNAL(textChanged(QString)), this, SLOT(ExchangeChanged(QString)));

    QLabel *l_bac = new QLabel();
    l_bac->setText(tr("Contest Name")+":");
    cb_cont_id = new QComboBox();
    QStringList lst_bc;
    for (int i = 0; i<COUNT_CONTEST; ++i)
        lst_bc << s_cont_name[i];
    cb_cont_id->addItems(lst_bc);
    cb_cont_id->setMaxVisibleItems(COUNT_CONTEST);//2.50
    cb_cont_id->setCurrentIndex(0);
    connect(cb_cont_id, SIGNAL(currentIndexChanged(QString)), this, SLOT(ExchangeChanged(QString)));
    
    QLabel *l_trmn = new QLabel();
    //l_trmn->setText("Multi-Two Station:");//Transmitter
    l_trmn->setText(tr("Transmitter")+":");
    l_trmn->setContentsMargins(0,0,0,0);
    cb_cabrillo_trmN = new QComboBox();
    QStringList lst_trmn;
    lst_trmn <<"None"<<"Run 1"<<"Run 2"; 
    cb_cabrillo_trmN->addItems(lst_trmn);
    cb_cabrillo_trmN->setCurrentIndex(0);
    cb_cabrillo_trmN->setMinimumWidth(80);
    
    QHBoxLayout *H_cont = new QHBoxLayout();
    H_cont->setContentsMargins ( 1, 1, 1, 1);
    H_cont->setSpacing(3);
    H_cont->addWidget(l_txsn);
    H_cont->addWidget(le_txsn);
    H_cont->addWidget(l_rxsn);
    H_cont->addWidget(le_rxsn);
    H_cont->addWidget(l_txex);
    H_cont->addWidget(le_txex);
    H_cont->addWidget(l_rxex);
    H_cont->addWidget(le_rxex);
    H_cont->addWidget(l_bac);
    H_cont->addWidget(cb_cont_id);
    H_cont->addWidget(l_trmn);
    H_cont->addWidget(cb_cabrillo_trmN);

    bt_corr = new QPushButton(bt_corr_txt);//" Apply Changes "
    //bt_corr->setFixedHeight(le_loc->sizeHint().height());
    connect(bt_corr, SIGNAL(clicked(bool)), this, SLOT(CorrContact()));
    bt_cancel = new QPushButton(bt_cancel_txt);//" Exit Edit Mode "
    //bt_cancel->setFixedHeight(le_loc->sizeHint().height());
    connect(bt_cancel, SIGNAL(clicked(bool)), this, SIGNAL(EndEdit()));
    QHBoxLayout *H_b = new QHBoxLayout();
    H_b->setContentsMargins ( 1, 1, 1, 1);
    H_b->setSpacing(3);
    H_b->addWidget(le_call);
    //H_b->setAlignment(le_call,Qt::AlignCenter);
    H_b->addWidget(le_txrst);
    //H_b->setAlignment(le_txrst,Qt::AlignRight);
    //H_b->addWidget(le_txsn);
    H_b->addWidget(le_rxrst);
    //H_b->setAlignment(le_rxrst,Qt::AlignRight);
    //H_b->addWidget(le_rxsn);
    H_b->addWidget(le_loc);
    //H_b->setAlignment(le_loc,Qt::AlignRight);

    //H_b->addWidget(l_comment);
    //H_b->setAlignment(l_comment,Qt::AlignRight);
    //H_b->addWidget(le_comment);

    H_b->addWidget(bt_cancel);
    //H_b->addWidget(bt_corr);
    H_dtm->addWidget(bt_corr);
    //H_dtm->setAlignment(bt_corr,Qt::AlignRight);

    QVBoxLayout *V_l = new QVBoxLayout(this);
    V_l->setContentsMargins ( 1, 1, 1, 1);
    V_l->setSpacing(2);
    V_l->addWidget(l_e);
    V_l->setAlignment(l_e,Qt::AlignCenter);
    V_l->addLayout(H_dtm);
    //V_l->setAlignment(H_dtm,Qt::AlignLeft);
    V_l->addLayout(H_b);
    V_l->addLayout(H_c);
    V_l->addLayout(H_cont);
    setLayout(V_l);

}
HvEditW::~HvEditW()
{}
void HvEditW::SetFont(QFont f)
{
    le_call->SetFont(f);
    le_txrst->SetFont(f);
    le_rxrst->SetFont(f);
    le_loc->SetFont(f);
    le_freq->SetFont(f);
}
bool HvEditW::FDCheck(QString fdt)
{
    bool f_fderr = true;
    QStringList lfd = fdt.split(" ");
    if (lfd.count()==2)//le_in->setStyleSheet("QLineEdit {background-color :palette(Base);}");
    {
        QString cat = lfd.at(0);//1A-32F
        QString sec = lfd.at(1);//sec
        int icatl = (int)cat.at(cat.count()-1).toLatin1();
        if (icatl>=(int)'A' && icatl<=(int)'F')
        {
            int icat = cat.midRef(0,cat.count()-1).toInt(); //qDebug()<<cat<<sec<<icat<<sec<<cat.mid(0,cat.count()-1);
            //if (icat>0 && icat<33)//need to be 1-32  pack77 no problem ???
            if (icat>0 && icat<33)
            {
                for (int i = 0; i < NSEC; ++i)
                {
                    if (sec==csec_77[i].trimmed())
                    {
                        f_fderr = false;
                        break;
                    }
                }
            }
        }
    }
    return f_fderr;
}
bool HvEditW::RUCheck(QString s)
{
    bool f_ruerr = true;
    int irxsn = le_rxsn->text().toInt();
    for (int i = 0; i < NUSCAN; ++i)
    {
        if (s==cmult_77[i].trimmed() || s=="DX" || irxsn>0)
        {
            f_ruerr = false;
            break;
        }
    }
    return f_ruerr;
}
void HvEditW::ExchangeChanged(QString)
{
    //FD 2B EMA
    //RU MA
    QString txstr = le_txex->text();
    QString rxstr = le_rxex->text();
    int cont_id = cb_cont_id->currentIndex(); //qDebug()<<cont_id<<str;
    //QString fdt = le_exchfd->text();
    if (cont_id==4)// FD
    {
        if (FDCheck(txstr))
            le_txex->setStyleSheet("QLineEdit {background-color :rgb(255, 255, 200) ;color: rgb(200, 0, 0)}");
        else
            le_txex->setStyleSheet("QLineEdit {background-color :palette(Base);}");
            
        if (FDCheck(rxstr))
            le_rxex->setStyleSheet("QLineEdit {background-color :rgb(255, 255, 200) ;color: rgb(200, 0, 0)}");
        else
            le_rxex->setStyleSheet("QLineEdit {background-color :palette(Base);}");
    } 
    else if (cont_id==9 || cont_id==10 || cont_id==11 || cont_id==12)//2.64 ALL RU
    {
        if (RUCheck(txstr))
            le_txex->setStyleSheet("QLineEdit {background-color :rgb(255, 255, 200) ;color: rgb(200, 0, 0)}");
        else
            le_txex->setStyleSheet("QLineEdit {background-color :palette(Base);}");
            
        if (RUCheck(rxstr))
            le_rxex->setStyleSheet("QLineEdit {background-color :rgb(255, 255, 200) ;color: rgb(200, 0, 0)}");
        else
            le_rxex->setStyleSheet("QLineEdit {background-color :palette(Base);}");
    }
    else
    {
    	le_txex->setStyleSheet("QLineEdit {background-color :palette(Base);}");
    	le_rxex->setStyleSheet("QLineEdit {background-color :palette(Base);}");	
    }
}
void HvEditW::Check(QString s_type)
{
    if (s_type == "call")
    {
        //if (le_their_call->getText().count()>1)
        if (THvQthLoc.isValidCallsign(le_call->getText()))
        {
            le_call->setError(false);
            le_call->setErrorColorLe(false);
        }
        else
        {
            le_call->setError(true);
            le_call->setErrorColorLe(true);
        }
    }

    if (s_type == "locator")
    {
        if (!le_loc->getText().isEmpty() && THvQthLoc.isValidLocator(le_loc->getText()))
        {
            le_loc->setError(false);
            le_loc->setErrorColorLe(false);
        }
        else
        {
            le_loc->setError(true);
            le_loc->setErrorColorLe(true);
        }
    }
}
void HvEditW::CorrContact()
{
    /*if (!THvQthLoc.isValidCallsign(le_call->getText()))
    {
        QString text = tr("Please set valid call sign");
        QMessageBox::critical(this, "MSHV", text, QMessageBox::Ok);
        //le_call->SetFocus();//za da otiva fokusa na call
        return;
    } 2.55 allow adding manually SWL Calls with "-" */
    //QDateTime dateTime2 = QDateTime::fromString("M1d1y9800:01:02","'M'M'd'd'y'yyhh:mm:ss");
    //QDateTime dateTime_s = QDateTime::fromString(de_bdate_s->text()+te_time_s->text(),"yyyyMMddhh:mm");
    //QDateTime dateTime_e = QDateTime::fromString(de_bdate_e->text()+te_time_e->text(),"yyyyMMddhh:mm");
    //QDateTime dateTime2 = dte_s->
    //dateTime_s.setDate(de_bdate_s->date)

    if (dte_s->dateTime().secsTo(dte_e->dateTime())<0)
    {
        QString text = tr("The starting Date and Time have to be earlier than the End Date and Time");
        QMessageBox::critical(this, "MSHV", text, QMessageBox::Ok);
        //le_call->SetFocus();//za da otiva fokusa na call
        return;
    }
    //qDebug()<<dateTime_s.secsTo(dateTime_e);

    QStringList list;
    /*QString str_rxsn = le_rxsn->getText();
    int rxn = str_rxsn.toInt();
    int d100 = rxn/100;
    int d10 = rxn/10%10;
    int d1 = rxn%10;
    str_rxsn = QString("%1%2%3").arg(d100).arg(d10).arg(d1);*/


    int id = cb_prop->currentIndex();
    QString propt = s_id_prop_mod[id];//None
    //QString propt = cb_prop->currentText();
    //if(propt=="None")
    //propt="";
    
    list<<dte_s->date().toString("yyyyMMdd")<<dte_s->time().toString("hh:mm")
    <<dte_e->date().toString("yyyyMMdd")<<dte_e->time().toString("hh:mm")<<le_call->getText()<<le_loc->getText()
    <<le_txrst->getText()<<le_rxrst->getText()<<Cb_mode->currentText()<<Cb_band->currentText()<<le_freq->getText()
    <<propt<<le_comment->text()<<s_enum_sec_sta<<le_txsn->text()<<le_rxsn->text()<<le_txex->text()<<le_rxex->text()
    <<QString("%1").arg(cb_cont_id->currentIndex())<<QString("%1").arg(cb_cabrillo_trmN->currentIndex())
    <<s_enum_sec_end<<s_dist;

    emit SendCorrContact(list, index_edit);

    le_call->SetFocus();//za da otiva fokusa na call

}
void HvEditW::SetEdit(QStringList list, int index)
{
    index_edit = index;
    le_call->SetText("");//zaradi duble qso
    first_dupe_flag = true;
    /*1          SSB         SSB
      2          CW          CW
      3          SSB         CW
      4          CW          SSB
      5          AM          AM
      6          FM          FM
      7          RTTY        RTTY
      8          SSTV        SSTV
      9          ATV         ATV*/

    dte_s->setDateTime(QDateTime::fromString(list.at(0)+list.at(1), "yyyyMMddhh:mm"));
    dte_e->setDateTime(QDateTime::fromString(list.at(2)+list.at(3), "yyyyMMddhh:mm"));
    //dte_s->setDate(QDate::fromString(list.at(0), "yyyyMMdd"));
    //dte_s->setTime(QTime::fromString(list.at(1), "hh:mm"));
    //dte_e->setDate(QDate::fromString(list.at(2), "yyyyMMdd"));
    //dte_e->setTime(QTime::fromString(list.at(3), "hh:mm"));

    //{"MSK144","JTMS","FSK441","FSK315","JT6M","ISCAT-A","ISCAT-B"};
    for (int i = 0; i<COUNT_MODE; ++i)//2.67
    {
    	if (list.at(8) == ModeStr(pos_mods[i]))
    	{
    		Cb_mode->setCurrentIndex(i);
    		break;    		
   		}   	
   	}
   	if 		(list.at(8) == "SSB") Cb_mode->setCurrentIndex(COUNT_MODE);
    else if (list.at(8) == "CW" ) Cb_mode->setCurrentIndex(COUNT_MODE+1);
    else if (list.at(8) == "FM" ) Cb_mode->setCurrentIndex(COUNT_MODE+2);

       
    int index1 = Cb_band->findText(list.at(9), Qt::MatchCaseSensitive);
    if (index1 >= 0) Cb_band->setCurrentIndex(index1);

    le_call->SetText(list.at(4));
    if (le_call->getText().isEmpty()) Check("call");

    le_txrst->SetText(list.at(6));
    le_rxrst->SetText(list.at(7));

    le_loc->SetText(list.at(5));

    QString tmpf = list.at(10);// freq 1.50
    tmpf.remove(".");
    tmpf.remove(",");
	if (tmpf.at(0) == '0') tmpf = tmpf.mid(1,tmpf.count()-1);//2.31 remove first zero 0.455.000
    le_freq->SetText(tmpf);// freq 1.50
    //le_comment->setText("frq rezerve list.at(10)");

    //le_comment->setText(list.at(11));//prop
    //index1 = cb_prop->findText(list.at(11), Qt::MatchCaseSensitive);
    index1 = 0;
    for (int i = 0; i<COUNT_PROP; ++i)
    {
        if (list.at(11)==s_id_prop_mod[i])
        {
            index1 = i;
            break;
        }
    }
    cb_prop->setCurrentIndex(index1);
    /*if (index1 >= 0)
        cb_prop->setCurrentIndex(index1);
    else
    	cb_prop->setCurrentIndex(0);*/

    le_comment->setText(list.at(12));//comment
    s_enum_sec_sta = list.at(13);        //enum seconds 00-59;
    s_enum_sec_end = list.at(20);        //enum seconds end 00-59;

    le_txsn->setText(list.at(14));
    le_rxsn->setText(list.at(15));
    le_txex->setText(list.at(16));
    le_rxex->setText(list.at(17));
    //s_cont_id = list.at(18);//contest id hiden
    int index2 = list.at(18).toInt(); //qDebug()<<index2;
    if (index2 >= 0) cb_cont_id->setCurrentIndex(index2);
        
    //contest MULTI-TWO hiden 
    index2 = list.at(19).toInt(); //qDebug()<<index2;
    if (index2 >= 0) cb_cabrillo_trmN->setCurrentIndex(index2);  
        
    s_dist = list.at(21);        //distance  

}

