#include "OE_ui_stitchlist.h"
#include "lib/qtmaterialtheme.h"
#include <iostream>

OE_ui_stitchList::OE_ui_stitchList(MainWindow* window, OE_root* root)
{
	this->root = root;
	this->window = window;
    setSelectionMode(QAbstractItemView::ExtendedSelection);
    setSelectionBehavior(QAbstractItemView::SelectRows);
	setDragEnabled(true);
	setDragDropMode(QAbstractItemView::InternalMove);
	viewport()->setAcceptDrops(true);
	setDropIndicatorShown(true);
	setDefaultDropAction(Qt::TargetMoveAction);

    setMouseTracking(true);

	setMinimumSize(100,0);

	setDragDropMode(QAbstractItemView::InternalMove);

	model = new QStandardItemModel();
	listdelegate = new ListviewDelegate();
	setItemDelegate(listdelegate);
	setModel(model);

	//getItems();
    refreshStitches();

    connect(getInterfaceDisplay(), SIGNAL(refreshStitchList()), this, SLOT(on_refreshStitchList()));
    connect(getInterfaceDisplay(), SIGNAL(refreshStitch(OE_stitchs*)), this, SLOT(on_refreshStitch(OE_stitchs*)));
    connect(selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleSelectionChanged()));
    connect(getInterfaceDisplay(), SIGNAL(stitchSelectionChange()), this, SLOT(on_refreshStitchList()));
    connect(this,SIGNAL(entered(QModelIndex)),this,SLOT(enteredSlot(QModelIndex)));

	showMaximized();


}

void OE_ui_stitchList::addItem(QColor color, QIcon icon, QIcon type, QIcon pattern, int stitchCount)
{

	QStandardItem *item = new QStandardItem();
	item->setData(color,ListviewDelegate::threadRole);
	item->setData(QString::number(model->rowCount()+1),ListviewDelegate::IndexRole);
	item->setData(QString::number(stitchCount),ListviewDelegate::NbpointsRole);
	item->setData(icon,ListviewDelegate::IconRole);
	item->setData(type,ListviewDelegate::typeRole);
    item->setData(pattern,ListviewDelegate::patternRole);

	item->setFlags(item->flags() & ~(Qt::ItemIsDropEnabled));//& ~Qt::ItemIsDragEnabled);
	model->appendRow(item);
}

void OE_ui_stitchList::addItem(QColor color, int stitchCount)
{

	QStandardItem *item = new QStandardItem();
	item->setData(color,ListviewDelegate::threadRole);
	item->setData(QString::number(stitchCount),ListviewDelegate::NbpointsRole);

	item->setFlags(item->flags() & ~(Qt::ItemIsDropEnabled));// & ~Qt::ItemIsDragEnabled);
	model->appendRow(item);
}

void  OE_ui_stitchList::addStitch(OE_stitchs* stitch)
{
    QColor threadColor = stitch->getThread()->getColor();
    OE_linkstitch* tmpLinkStitch = dynamic_cast<OE_linkstitch*>(stitch);
    if (tmpLinkStitch)
    {
        addItem(threadColor, stitch->getNpts());
        return;
    }

    OE_linestitch* tmpLineStitch = dynamic_cast<OE_linestitch*>(stitch);
    if (tmpLineStitch)
    {
        static QIcon lineStitchIcon = QIcon(":/resources/line_stitch.svg");
        addItem(threadColor, lineStitchIcon, lineStitchIcon, lineStitchIcon, stitch->getNpts());
        return;
    }

    OE_birailstitch* tmpBirailStitch = dynamic_cast<OE_birailstitch*>(stitch);
    if (tmpBirailStitch)
    {
        static QIcon birailStitchIcon = QIcon(":/resources/birail_stitch.svg");
        addItem(threadColor, birailStitchIcon, birailStitchIcon, birailStitchIcon, stitch->getNpts());
        return;
    }

    OE_fillstitch* tmpFillStitch = dynamic_cast<OE_fillstitch*>(stitch);
    if (tmpFillStitch)
    {
        static QIcon fillStitchIcon = QIcon(":/resources/fill_stitch.svg");
        addItem(threadColor, fillStitchIcon, fillStitchIcon, fillStitchIcon, stitch->getNpts());
        return;
    }

    OE_staticstitch* tmpStaticStitch = dynamic_cast<OE_staticstitch*>(stitch);
    if (tmpStaticStitch)
    {
        static QIcon staticStitchIcon = QIcon(":/resources/static_stitch.svg");
        addItem(threadColor, staticStitchIcon, staticStitchIcon, staticStitchIcon, stitch->getNpts());
        return;
    }


	//root->document->stitchs
	//root->document->selectedStitchs
}


void  OE_ui_stitchList::refreshStitches()
{
    if (getDocument())
    {
        model->clear();
        QItemSelection selection;
        int id = 0;
        for (auto stitch : getDocument()->stitchs)
        {
            addStitch(stitch);
            auto it = std::find(getDocument()->selectedStitchs.begin(), getDocument()->selectedStitchs.end(), stitch);
            if(it != getDocument()->selectedStitchs.end())

                selection.merge(QItemSelection(model->index(id, 0), model->index(id, 0)), QItemSelectionModel::Select | QItemSelectionModel::Rows);

            id++;
        }
        selectionModel()->blockSignals(true);
        selectionModel()->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows);
        selectionModel()->blockSignals(false);
    }
}

void OE_ui_stitchList::on_refreshStitchList()
{
    refreshStitches();
}
void OE_ui_stitchList::on_refreshStitch(OE_stitchs* stitch)
{
    //refreshStitches();
}

void OE_ui_stitchList::handleSelectionChanged()
{
    std::list<int> stitchesId;
    foreach(const QModelIndex &index, selectionModel()->selectedIndexes())
        stitchesId.push_back(index.row());
    getController()->selectStitches(stitchesId, true);
    getInterfaceDisplay()->update();
}

void OE_ui_stitchList::dropEvent(QDropEvent *event)
{
    QModelIndex index = indexAt(event->pos());
    DropIndicatorPosition pos = this->dropIndicatorPosition();
    if (pos == DropIndicatorPosition::BelowItem)
        getController()->moveInListSelectedStitches(index.row()+1);
    else
        getController()->moveInListSelectedStitches(index.row());

    getInterfaceDisplay()->update();
    refreshStitches();
}

void OE_ui_stitchList::keyPressEvent(QKeyEvent *event)
{
    if(event->key()==Qt::Key_Right) {
        QKeyEvent* eventDown = new QKeyEvent(event->type(), Qt::Key_Down, event->modifiers());
        QListView::keyPressEvent(eventDown);
        return;
    }
    if(event->key()==Qt::Key_Left) {
        QKeyEvent* eventUp = new QKeyEvent(event->type(), Qt::Key_Up, event->modifiers());
        QListView::keyPressEvent(eventUp);
        return;
    }
    QListView::keyPressEvent(event);
}

void OE_ui_stitchList::leaveEvent(QEvent *event)
{
   QListView::leaveEvent(event);
   getInterfaceDisplay()->higligtedStitch = nullptr;
}

void OE_ui_stitchList::enteredSlot(QModelIndex index)
{
    std::list<OE_stitchs*>::iterator it = getDocument()->stitchs.begin();
        std::advance(it, index.row());

    getInterfaceDisplay()->higligtedStitch = *it;
    getInterfaceDisplay()->update();
}

OE_controller* OE_ui_stitchList::getController()
{
    return this->root->interfaceDisplay->getController();
}

OE_interfaceDisplay* OE_ui_stitchList::getInterfaceDisplay()
{
    return this->root->interfaceDisplay;
}

OE_document* OE_ui_stitchList::getDocument()
{
    return this->root->interfaceDisplay->getDocument();
}
