#include "SettingsWindow.h"
#include <QGridLayout>
#include <QLabel>
#include <QVBoxLayout>
#include "MasterCtrl.h"
#include <QFileDialog>



CSettingsWindow::CSettingsWindow()
{
    resize(600,600);

    QVBoxLayout *MainLayout = new QVBoxLayout;
    QWidget *mPagesContainer = new QWidget(this);

    mLoraSettingsPage = new CLoraSettingsGui(mPagesContainer);

    mOptionsTabBar = new QTabBar();
    mOptionsTabBar->addTab("SMS");
    mOptionsTabBar->addTab("Network");
    mOptionsTabBar->addTab("Contacts");
    mOptionsTabBar->addTab("Chalet");
    mOptionsTabBar->resize(this->geometry().width(),mOptionsTabBar->height());
    MainLayout->addWidget(mOptionsTabBar);


    //////////////////VOIP.MS config page/////////////////////

    mSMSPage = new QWidget(mPagesContainer);
 //   mVoipPage->resize(this->size());

    QGridLayout *mSMSPageLayout = new QGridLayout;


    QLabel *Label;
    mVoipMSUsername = new QLineEdit;
    Label = new QLabel("Voip.ms Username: ");
    mSMSPageLayout->addWidget(Label,0,1,1,1);
    mSMSPageLayout->addWidget(mVoipMSUsername,0,2,1,2/*,Qt::AlignLeft*/);

    Label = new QLabel("Voip.ms Password: ");
    mVoipMSPassword = new QLineEdit;
    mVoipMSPassword->setEchoMode(QLineEdit::Password);
    mSMSPageLayout->addWidget(Label,1,1,1,1);
    mSMSPageLayout->addWidget(mVoipMSPassword,1,2,1,1/*,Qt::AlignLeft*/);

    mRetreiveDIDSButton = new QPushButton("Get DIDs");
    connect(mRetreiveDIDSButton,SIGNAL(clicked(bool)),this,SLOT(RetreiveDIDButtonClicked(bool)));
    mSMSPageLayout->addWidget(mRetreiveDIDSButton,1,3,1,1);


    Label = new QLabel("DID:");
    mDIDSelectionDropList = new QComboBox();
    mSMSPageLayout->addWidget(Label,2,1,1,1);
    mSMSPageLayout->addWidget(mDIDSelectionDropList,2,2,1,1);


    mVoipMSCalendar = new QCalendarWidget;
    Label = new QLabel("SMS retreival start date:");
    mSMSPageLayout->addWidget(Label,3,1,1,1);
    mSMSPageLayout->addWidget(mVoipMSCalendar,4,1,1,4);

    mDoneButton = new QPushButton("Done");
    MainLayout->addWidget(mDoneButton);
    connect(mDoneButton,SIGNAL(clicked(bool)),this,SLOT(DoneButtonClicked(bool)));




    mSMSPage->setLayout(mSMSPageLayout);
    mSMSPage->show();



    //////////////////VOIP.MS config page/////////////////////

    mContactsPage = new QWidget(mPagesContainer);
    mContactsPage->resize(400,400);

    mDefaultContactPixmap = new QPixmap(QPixmap("./Ico/contact.png").scaled(75,75));

    QGridLayout *mContactsPageLayout = new QGridLayout;

    mContactsList = new QTableWidget(0,2);
    mContactsList->setSelectionBehavior(QAbstractItemView::SelectRows);
    mContactsList->setSelectionMode(QAbstractItemView::SingleSelection);
    mContactsList->clearContents();
    mContactsList->setRowCount(0);
    mContactsList->setHorizontalHeaderLabels(QStringList() << "Contact" << "Name");
    mContactsPageLayout->addWidget(mContactsList,0,0,1,3);
    connect(mContactsList,SIGNAL(cellDoubleClicked(int,int)),SLOT(TableDoubleClicked(int,int)));
    //connect(mLogsTable,SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),this,SLOT(TableCurItemChanged(QTableWidgetItem*,QTableWidgetItem*)));
    connect(mContactsList,SIGNAL(itemSelectionChanged()),this,SLOT(TableCellSelected(/*int,int*/)));



    Label = new QLabel("Contact Name: ");
    mContactsPageLayout->addWidget(Label,1,1,1,1);
    mContactNameEdit = new QLineEdit();
    mContactsPageLayout->addWidget(mContactNameEdit,1,2,1,1);

    Label = new QLabel("Contact Raw Number: ");
    mContactsPageLayout->addWidget(Label,2,1,1,1);
    mContactRawNbrEdit = new QLineEdit();
   // mContactRawNbrEdit->setInputMask("9");
    mContactsPageLayout->addWidget(mContactRawNbrEdit,2,2,1,1);

    Label = new QLabel("Contact Number: ");
    mContactsPageLayout->addWidget(Label,3,1,1,1);
    mContactNbrEdit = new QLineEdit();
    mContactNbrEdit->setDisabled(true);
    mContactsPageLayout->addWidget(mContactNbrEdit,3,2,1,1);

    mContactPixmapLabel = new QLabel();
    mContactPixmapLabel->setPixmap(*mDefaultContactPixmap);
    mContactsPageLayout->addWidget(mContactPixmapLabel,1,0,2,1);


    mSelectContactPicBtn = new QPushButton("Choose");
    mContactsPageLayout->addWidget(mSelectContactPicBtn,3,0,1,1);
    connect(mSelectContactPicBtn,SIGNAL(clicked(bool)),this,SLOT(SelectContactPicClicked(bool)));


    mNewContactBtn =  new QPushButton("New");
    mContactsPageLayout->addWidget(mNewContactBtn,4,1,1,1);
    connect(mNewContactBtn,SIGNAL(clicked(bool)),this,SLOT(NewContactClicked(bool)));

    mSaveContactBtn =  new QPushButton("Save");
    mContactsPageLayout->addWidget(mSaveContactBtn,4,2,1,1);
    connect(mSaveContactBtn,SIGNAL(clicked(bool)),this,SLOT(SaveContactClicked(bool)));

    mDeleteContactBtn =  new QPushButton("Delete Contact");
    mContactsPageLayout->addWidget(mDeleteContactBtn,4,0,1,1);
    connect(mDeleteContactBtn,SIGNAL(clicked(bool)),this,SLOT(DeleteContactClicked(bool)));

    mContactsPage->setLayout(mContactsPageLayout);
    mContactsPage->hide();


    MainLayout->addWidget(mPagesContainer);
    setLayout(MainLayout);

    connect(mOptionsTabBar,SIGNAL(currentChanged(int)),this,SLOT(TabBarClicked(int)));

}

CSettingsWindow::~CSettingsWindow()
{

}

void CSettingsWindow::TabBarClicked(int TabIndex)
{
    if(TabIndex == 0)//SMS
    {
        mSMSPage->show();
        mContactsPage->hide();


    }
    else if(TabIndex == 1)//Network
    {
        mSMSPage->hide();
        mContactsPage->hide();
        mLoraSettingsPage->hide();

    }
    else if(TabIndex == 2)//Contacts
    {
        mSMSPage->hide();
        mLoraSettingsPage->hide();
        mContactsPage->show();

    }
    else if(TabIndex == 3) //Lora
    {
        mSMSPage->hide();
        mContactsPage->hide();
        mLoraSettingsPage->show();
    }
}

void CSettingsWindow::RetreiveDIDButtonClicked(bool checked)
{
    Q_UNUSED(checked)

    if(mVoipMSUsername->text().isEmpty() || mVoipMSPassword->text().isEmpty())
    {
        return;
    }


    mProgramHandle->FetchDIDsRequest(mVoipMSUsername->text(),mVoipMSPassword->text());
    qDebug("CLick!");
}

void CSettingsWindow::DIDsListFetched(QStringList DIDs)
{
    if(DIDs.size() == 0)
    {

    }
    else
    {
        mDIDSelectionDropList->clear();
        for(int i = 0; i < DIDs.size(); i++)
        {
            mDIDSelectionDropList->addItem(DIDs.at(i));
        }
    }
}

unsigned int CSettingsWindow::SetSettingsData(CSettings *SettingsData)
{
    mVoipMSPassword->setText(SettingsData->mVoipMSSettings.mPassword);
    mVoipMSUsername->setText(SettingsData->mVoipMSSettings.mUsername);
    mDIDSelectionDropList->clear();
    mDIDSelectionDropList->addItem(SettingsData->mVoipMSSettings.mDefaultDID);
    mVoipMSCalendar->setSelectedDate(SettingsData->mVoipMSSettings.mStartDate);
    mLoraSettingsPage->SetSettings(SettingsData);

    return RET_OK;
}

void CSettingsWindow::DoneButtonClicked(bool checked)
{
    Q_UNUSED(checked)

    CSettings *Settings = new CSettings;
    Settings->mVoipMSSettings.mDefaultDID = mDIDSelectionDropList->currentText();
    Settings->mVoipMSSettings.mPassword = mVoipMSPassword->text();
    Settings->mVoipMSSettings.mStartDate = mVoipMSCalendar->selectedDate();
    Settings->mVoipMSSettings.mUsername = mVoipMSUsername->text();
    Settings->mChaletComPort = mLoraSettingsPage->GetChaletLoraComPort();
    Settings->mChaletLoraAddress = mLoraSettingsPage->GetChaletLoraAddress();
    Settings->mChaletLoraChannel = mLoraSettingsPage->GetChaletLoraChannel();
    Settings->mChaletUseLoraIF = mLoraSettingsPage->GetChaletUseLoraIF();

    mProgramHandle->SaveSettings(Settings);
    mProgramHandle->SettingsWindowClosed();
    delete Settings;

    this->hide();
}

void CSettingsWindow::SelectContactPicClicked(bool checked)
{
    Q_UNUSED(checked)

    QString fileName = QFileDialog::getOpenFileName(this,tr("Select Image"), "", tr("Image Files (*.png *.jpg *.bmp)"));
    if(fileName.isNull())
    {
        return;
    }

//    int Index =GetCurSelectedItemIndexInTable();

//    if(Index >= 0)
//    {
//        mProgramHandle->GetContactRepository()->GetContactPtr(Index)->SetContactImage(fileName);
//    }

   // mContactPixmap = mProgramHandle->GetContactRepository()->GetContactPtr(Index)->mContactPicture;

    mContactPixmap = QPixmap(fileName);
    mContactPixmapLabel->setPixmap(mContactPixmap.scaled(75,75));

}

void CSettingsWindow::SaveContactClicked(bool checked)
{
    Q_UNUSED(checked)
    CContact NewContact(mContactRawNbrEdit->text(),mContactNameEdit->text(),&mContactPixmap);
    int index = GetCurSelectedItemIndexInTable();

    mProgramHandle->GetContactRepository()->ChangeContact(index,NewContact);

    UpdateContacts();

  //  delete NewContact;

}

void CSettingsWindow::DeleteContactClicked(bool checked)
{
    Q_UNUSED(checked)
    int Index =GetCurSelectedItemIndexInTable();

    if(Index >= 0)
    {
        mProgramHandle->GetContactRepository()->DeleteContact(Index);
    }

    UpdateContacts();
    mContactsList->setCurrentCell(0,0);
}

void CSettingsWindow::NewContactClicked(bool checked)
{
    Q_UNUSED(checked)
    CContact NewContact("---");
    mProgramHandle->GetContactRepository()->AddContact(NewContact);

    UpdateContacts();
    mContactsList->setCurrentCell(mContactsList->rowCount()-1,0);

}

int CSettingsWindow::UpdateContacts()
{
    QList<CContact> *ContactsList;
    ClearTable();
    ContactsList = mProgramHandle->GetContactRepository()->GetContacts();

    mContactsList->setRowCount(ContactsList->size());

    for(int i = 0; i < ContactsList->size(); i++)
    {
        QTableWidgetItem * NewItem = new QTableWidgetItem(ContactsList->at(i).mContactNumber);
        NewItem->setData(Qt::UserRole,QVariant(i));
        NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        mContactsList->setItem(i,0,NewItem);

        NewItem = new QTableWidgetItem(ContactsList->at(i).mContactName);
        NewItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        mContactsList->setItem(i,1,NewItem);
    }


    mContactsList->resizeColumnsToContents();

    return RET_OK;
}

void CSettingsWindow::ClearTable()
{
    for(int Col = 0; Col < mContactsList->columnCount(); Col++)
        {
            for(int Row = 0; Row < mContactsList->rowCount(); Row++)
            {
                delete mContactsList->item(Row,Col);
                //mLogsTable->item(Row,Col) = 0;
            }
        }
        mContactsList->setRowCount(0);
        mContactsList->clearContents();
}

void CSettingsWindow::TableCellSelected(/*int row, int col*/)
{
    int Selection = GetCurSelectedItemIndexInTable();

    if(Selection == -1)
        return;

    CContact SelectedContact;
    mProgramHandle->GetContactRepository()->GetContact(Selection,SelectedContact);

    mContactRawNbrEdit->setText(SelectedContact.mRAWContactNbr);
    mContactNameEdit->setText(SelectedContact.mContactName);
    mContactNbrEdit->setText(SelectedContact.mContactNumber);

    mContactPixmap = SelectedContact.mContactPicture;
    mContactPixmapLabel->setPixmap(mContactPixmap.scaled(75,75));

}

int CSettingsWindow::GetCurSelectedItemIndexInTable()
{
    QList<QTableWidgetItem*> list = mContactsList->selectedItems();

    if(list.size() == 0)
        return - 1;

    int Selection = -1;
    for(int i = 0; i < list.size(); i++)
    {
        if(list.at(i)->column() == 0)
        {
            Selection = list.at(i)->data(Qt::UserRole).toInt();
            break;
        }
    }

    return Selection;
}

void CSettingsWindow::TableDoubleClicked(int row, int col)
{

}
