/* MSHV LogList
 * 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 "hvloglist.h"

//#include <QtGui>

/*HvHeaderLog::HvHeaderLog( Qt::Orientation orientation, QWidget *parent )
        : QHeaderView(orientation, parent)
{
    //setResizeMode (QHeaderView::Stretch);
}
HvHeaderLog::~HvHeaderLog()
{}*/
HvStandardItemModel::HvStandardItemModel(QObject *parent)
        : QStandardItemModel(parent)
{}
HvStandardItemModel::~HvStandardItemModel()
{}	
bool hv_sort_aorder_(const QStringList &d1,const QStringList &d2)
{
    return d1.at(21).toInt() < d2.at(21).toInt();
}
bool hv_sort_dorder_(const QStringList &d1,const QStringList &d2)
{
    return d1.at(21).toInt() > d2.at(21).toInt();
}
void HvStandardItemModel::sort(int column, Qt::SortOrder order)
{
    if (column==21)// distance special sort
    {
    	//qDebug()<<rowCount();
    	//if (column >= columnCount()) return;
    	if (rowCount() < 2) return; //if have min 2 item    	
        list_.clear();
        for (int i = 0; i < rowCount(); ++i)
        {
            QStringList itml;
            for (int j = 0; j < columnCount(); ++j)
            {
                itml << item(i,j)->text();
            }
            list_.append(itml); 
        }
         
        if (order == Qt::AscendingOrder)	//Ascending
            std::sort(list_.begin(), list_.end(), hv_sort_aorder_);
        else 								//Descending
            std::sort(list_.begin(), list_.end(), hv_sort_dorder_);     
           
        for (int i = 0; i < rowCount(); ++i)
        {
            for (int j = 0; j < columnCount(); ++j)
            {
                QStringList l = list_.at(i);
                QString g = l.at(j);
                //QStandardItem *item = new QStandardItem(g);
                QStandardItem *item = itemFromIndex(index(i, j));
                item->setText(g);
                //item->setEditable(false);
                //item->setTextAlignment(Qt::AlignLeft);
                setItem(i,j,item);
            }
        }
        //end bug qt5.7 if setItem 0 row show hiden columns
        emit EmitSortEnd();
    }
    else
        QStandardItemModel::sort(column, order);
}

HvLogList::HvLogList(bool indsty,QWidget *parent)
        : QTreeView(parent)
{
    setMinimumSize(795, 200);
    //this->set
    last_logged_dt = "_";
    enum_sec_logged = 0;

    setRootIsDecorated(false);
    setModel(&model);
    //THvHeader = new HvHeaderLog(Qt::Horizontal);
    THvHeader = new QHeaderView(Qt::Horizontal);
    

    connect(THvHeader, SIGNAL(sectionPressed(int)),this,SIGNAL(SortClicked(int)));

    setHeader(THvHeader);
    setAllColumnsShowFocus(true);  // za da o4ertae delia row

    //setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    setSelectionBehavior(QAbstractItemView::SelectRows);
    //setSelectionMode(QAbstractItemView::ExtendedSelection);//QAbstractItemView::SingleSelection


    setDragDropMode(QAbstractItemView::NoDragDrop);//QAbstractItemView::InternalMove
    setDragEnabled (false);
    // setAcceptDrops(true);
    setVerticalScrollMode(QAbstractItemView::ScrollPerItem);// tova e za na mi6kata whella i dragdrop QAbstractItemView::ScrollPerPixel
    setAutoScroll(true); //for lz2pr s tova tarsi samo v 1 colona i za scroll pri drag
    //setAutoScroll(false);

    QPalette PaletteL = palette();
    PaletteL.setColor(QPalette::Shadow, QColor(120,120,120));// zaradi bordera okantovaneto na lista
    setPalette(PaletteL);

    QStringList list_A;
    //list_A <<"Date"<<"UTC Start"<<"Date End"<<"UTC End"<<"Callsign"<<"Locator"<<"TXRpt"<<"RXRpt"<<"Mode"
    //<<"Band"<<"Freq kHz"<<"Prop"<<"Comment";
    list_A <<tr("Date")<<tr("Start")<<"Date End"<<tr("End")<<tr("Callsign")<<tr("Locator")<<"TXRpt"<<"RXRpt"<<tr("Mode")
    <<tr("Band")<<"Freq kHz"<<tr("Prop")<<tr("Comment")<<"secSta"<<"TXSn"<<"RXSn"<<"TXExch"<<"RXExch"<<"Cid"
    <<"Cmt"<<"secDnd"<<tr("Distance");
    model.setHorizontalHeaderLabels(list_A);

    THvHeader->setSectionResizeMode(QHeaderView::Fixed);//qt5

	HideSections();
    /*THvHeader->hideSection(2);  //date end  hiden
    THvHeader->hideSection(13); //enum seconds 00-59 hiden
    THvHeader->hideSection(18); //contest id hiden
    THvHeader->hideSection(19); //contest MULTI-TWO hiden
    THvHeader->hideSection(20); //enum seconds end 00-59 hiden*/

    //THvHeader->setResizeMode(2, QHeaderView::Fixed);
    THvHeader->resizeSection(0, 80);//0  //78 date start 125%
    THvHeader->resizeSection(1, 60);//1  //  70 utc time start 125%
    THvHeader->resizeSection(2, 78);//2  //78 date end  hiden
    THvHeader->resizeSection(3, 60);//3  //  65 utc time end 125%
    THvHeader->resizeSection(4, 80);//4  // call
    THvHeader->resizeSection(5, 75);//5  //70 loc
    THvHeader->resizeSection(6, 50);//6  // txrpt
    THvHeader->resizeSection(7, 50);//7  // rxrpt
    THvHeader->resizeSection(8, 68);//8  // mode 125%
    THvHeader->resizeSection(9, 75);//9  //100 75 band 125%
    THvHeader->resizeSection(10, 70);//10  // reserve for freq hv 1.31
    THvHeader->resizeSection(11, 50);//11 // Propagation
    THvHeader->resizeSection(12, 100);//12 // commemt
    THvHeader->resizeSection(13, 25);//enum seconds 00-59 hiden      		13
    THvHeader->resizeSection(14, 45);//my tx sn contest               	    14
    THvHeader->resizeSection(15, 45);//my rx sn contest               	    15
    THvHeader->resizeSection(16, 55);//my tx exch contest            		16
    THvHeader->resizeSection(17, 55);//my rx exch contest           		17
    THvHeader->resizeSection(18, 20); //contest id hiden                    18
    THvHeader->resizeSection(19, 20); //contest MULTI-TWO hiden             19
    THvHeader->resizeSection(20, 20); //enum seconds end 00-59 hiden        20
    THvHeader->resizeSection(21, 75); //distance					        21
    //THvHeader->resizeSection(22, 75); //reserve					        22
    //THvHeader->resizeSection(23, 75); //reserve					        23
    //THvHeader->resizeSection(24, 75); //reserve					        24

    //THvHeader->moveSection(21,6);
    //THvHeader->moveSection(21,11);
    THvHeader->moveSection(21,8);

    //THvHeader->setSectionResizeMode(4, QHeaderView::ResizeToContents);//no work bug in qt5.7
    /*THvHeader->setSectionResizeMode(0, QHeaderView::Stretch);//1.81 for font
       THvHeader->setSectionResizeMode(5, QHeaderView::Stretch);//1.81 for font
       THvHeader->setSectionResizeMode(8, QHeaderView::Stretch);//1.81 for font
       THvHeader->setSectionResizeMode(9, QHeaderView::Stretch);//band 1.81 for font
       THvHeader->setSectionResizeMode(10, QHeaderView::Stretch);//1.81 for font
       //THvHeader->setSectionResizeMode(11, QHeaderView::Stretch);//Propagation 1.81 for font

       THvHeader->setSectionResizeMode(4, QHeaderView::Stretch);// qt5.7*/
    //THvHeader->setSectionResizeMode(12, QHeaderView::Stretch);//qt5 comment
    THvHeader->setSectionResizeMode(QHeaderView::Interactive);//2.01
    //THvHeader->setSectionResizeMode(QHeaderView::Stretch);//2.01

    //THvHeader->resizeSection(8, 35);
    //THvHeader->resizeSection(9, 46);
    //THvHeader->resizeSection(10, 70);
    //THvHeader->resizeSection(11, 70);

    setSortingEnabled(true);
    connect(&model,SIGNAL(EmitSortEnd()),this,SLOT(HideSections()));//2.57

    //setSelectionMode(QAbstractItemView::SingleSelection);
    setSelectionMode(QAbstractItemView::ExtendedSelection);
    //2.31 false for "\n" jt6m=6 jtms=1
    setUniformRowHeights(true);//2.30 fast wiev

    //QFont font("arial", 10);  // times new roman // slaga se tuk zaradi resize coll
    //QFont f_t = font();
    //f_t.setPointSize(10);
    //setFont(f_t);

    ActiveIndex = -1;

    if (indsty)
    {
        ActiveRowText = QColor(255,250,250);
        ActiveRowBackg = QColor(0,150,0);
    }
    else
    {
        ActiveRowText = QColor(255,0,0);
        ActiveRowBackg = QColor(0,255,0);
    }
    clipboard = QApplication::clipboard();
    // DrawDropLinePosY = -1;

    //this->setAlternatingRowColors(true);
    //model->setfil
}
HvLogList::~HvLogList()
{}
void HvLogList::HideSections()
{
	THvHeader->hideSection(2);  //date end  hiden
    THvHeader->hideSection(13); //enum seconds 00-59 hiden
    THvHeader->hideSection(18); //contest id hiden
    THvHeader->hideSection(19); //contest MULTI-TWO hiden
    THvHeader->hideSection(20); //enum seconds end 00-59 hiden
}
void HvLogList::paintEvent(QPaintEvent *event)
{
    QPainter painter(viewport());
    QModelIndex index = model.index(ActiveIndex, 1, QModelIndex());
    painter.fillRect(QRect(0,visualRect(index).y(),width(),visualRect(index).height()), ActiveRowBackg);
    QTreeView::paintEvent(event);
}
void HvLogList::drawRow(QPainter *painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    QStyleOptionViewItem opt = option;

    if (index.row() == ActiveIndex)
        opt.palette.setColor(QPalette::HighlightedText, ActiveRowText);
    else
        opt.palette.setBrush(QPalette::HighlightedText, palette().highlightedText());

    if (index.row() == ActiveIndex)
        opt.palette.setColor(QPalette::Text, ActiveRowText);
    else
        opt.palette.setBrush(QPalette::Text, palette().text());

    if (index.row() == ActiveIndex)
        opt.palette.setColor(QPalette::Highlight, ActiveRowBackg);
    else
        opt.palette.setBrush(QPalette::Highlight, palette().highlight());

    QTreeView::drawRow(painter, opt, index);
}
void HvLogList::SetEditRow(int numbr)
{
    ActiveIndex = numbr;
    viewport()->update();
}
void HvLogList::mouseDoubleClickEvent(QMouseEvent * event)
{
    if (event->button() == Qt::LeftButton)
        emit EmitDoubleClick();
    QTreeView::mousePressEvent(event);
}
/*
void HvLogList::mousePressEvent ( QMouseEvent * event)
{
    QTreeView::mousePressEvent(event);
    if (event->button() == Qt::RightButton)
        SendRightClick();

}
*/
void HvLogList::InsertItem_hv(QStringList list)
{
    if (!list.isEmpty())
    {
        QList<QStandardItem *> qlsi;
        int collumn = 0;

        for (QStringList::iterator it =  list.begin(); it != list.end(); ++it)
        {
            QString itxt = QString(*it);            
            if (!itxt.isEmpty()) itxt = itxt.trimmed();//2.63 protection

            if (collumn==13 && itxt.isEmpty())//1.82 enum seconds 00-59;
            {
                QString dt_start = list.at(0)+list.at(1);
                if (dt_start == last_logged_dt)
                {
                    if (enum_sec_logged<59)
                        enum_sec_logged++;
                }
                else
                    enum_sec_logged = 0;
                itxt = QString("%1").arg(enum_sec_logged,2,10,QChar('0'));
                last_logged_dt = dt_start;
            }
            if (collumn==20 && itxt.isEmpty())//2.41 enum seconds end 00-59;
            {
                itxt = QString("%1").arg(enum_sec_logged,2,10,QChar('0'));
            }


            if (collumn==10)//freq 1.50
            {
                int k = itxt.count();
                k -= 3;
                if (k>0)
                    itxt.insert(k,".");//KHz 1.50
                else if (!itxt.isEmpty())
                    itxt.prepend("0.");//2.31
            }

            QStandardItem *item = new QStandardItem(itxt);
            //if (collumn==21) item->setTextAlignment(Qt::AlignRight); //res=res.rightJustified(5,' ');
            item->setEditable(false);
            qlsi.append(item);
            collumn++;
        }
        //model.insertRow(model.rowCount(), qlsi);
        model.appendRow(qlsi);
        //this->setCurrentIndex(model.index(model.rowCount()-1,0));
        //this->scrollTo(model.index(model.rowCount()-1,0));
    }
}
void HvLogList::SetItem_hv(QStringList list,int index_edit)
{
    //int column_numb = 0;
    //for (QStringList::iterator it =  list.begin(); it != list.end(); ++it)
    for (int j = 0; j < list.count(); ++j)
    {
        // end bug qt5.7 if setItem 0 row show hiden columns
        bool isHidenCol = THvHeader->isSectionHidden(j);
        QString itxt = list.at(j);//QString(*it);        
        if (!itxt.isEmpty()) itxt = itxt.trimmed();//2.63 protection

        if (j==10)//freq 1.50
        {
            int k = itxt.count();
            k -= 3;
            if (k>0)
                itxt.insert(k,".");//KHz 1.50
            else if (!itxt.isEmpty())
                itxt.prepend("0.");//2.31
        }

        //QStandardItem *item = new QStandardItem(itxt);
        QStandardItem *item = model.itemFromIndex(model.index(index_edit, j));
        item->setText(itxt);       
        //item->setEditable(false);
        //item->setTextAlignment(Qt::AlignLeft);
        model.setItem(index_edit,j,item);
        // end bug qt5.7 if setItem 0 row show hiden columns
        if (isHidenCol) THvHeader->hideSection(j);
        //column_numb++;
    }
    setCurrentIndex(model.index(index_edit, 1, QModelIndex()));// ina4e ne refreshva 1 row
}
void HvLogList::Clear_List()
{
    for (int i = model.rowCount()-1; i >= 0; --i) // ok pravilno hv
        model.removeRow(i);
}
void HvLogList::DeleteSel()
{

    /*if (!selectionModel()->selection().empty())
    {    
        QModelIndex index = selectedIndexes()[0];
        //setAutoScroll(false);
        this->model.removeRow(index.row());
        //setAutoScroll(true);  // za da ne skrolira pri iztrivane kam poslednia markiran
        //RefreshDellData(model().rowCount());
        //SendDellData(str_n);
    }*/

    if (!selectionModel()->selection().empty())
    {
        setAutoScroll(false); //2.21 bez towa bavi za da ne skrolira pri iztrivane kam poslednia markiran
        QItemSelection selection( selectionModel()->selection() );

        QList<int> rows;
        foreach( const QModelIndex & index, selection.indexes() )
        {
            rows.append( index.row() );
        }

        //q_Sort(rows);
        std::sort(rows.begin(),rows.end());

        int prev = -1;
        for ( int i = rows.count() - 1; i >= 0; i -= 1 )
        {
            int current = rows[i];
            if ( current != prev )
            {
                model.removeRows( current, 1 );
                prev = current;
            }
        }
        setAutoScroll(true);  //2.21 bez towa bavi za da ne skrolira pri iztrivane kam poslednia markiran
    }
}
void HvLogList::keyPressEvent(QKeyEvent * event)
{
    if (event->matches(QKeySequence::Copy) && !selectionModel()->selection().empty() )
    {
        QModelIndexList lst = selectionModel()->selectedRows(0);
        QList<int> rows;
        foreach( const QModelIndex & index, lst )
        {
            rows.append( index.row() );
        }
        //q_Sort(rows);
        std::sort(rows.begin(),rows.end());
        QString str_n;
        for (int j = 0; j < rows.count(); j++)
        {

            for (int i = 0; i < model.columnCount(); i++)
            {
                str_n.append(model.item(rows[j], i)->text());
                if (i < model.columnCount()-1)
                    str_n.append(" ");
            }
            if (j < rows.count()-1)
                str_n.append("\n");
        }
        clipboard->setText(str_n);
    }
    else // vazno da e else ina4e kopira samo edna kletka
        QTreeView::keyPressEvent(event); // za da raboti keybord shortkeys Application
}
