/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2018 Univ. Grenoble Alpes, CNRS, TIMC-IMAG UMR 5525 (GMCAO)
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

// -- Core stuff
#include "Action.h"
#include "MedicalImageViewer.h"
#include "InteractiveViewer.h"
#include "Application.h"

//-- Qt stuff
#include <QColorDialog>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QToolBar>

namespace camitk {
MedicalImageViewer* MedicalImageViewer::singleton = nullptr;

MedicalImageViewer* MedicalImageViewer::getInstance() {
    if (!singleton) {
        singleton = new MedicalImageViewer();
    }

    return singleton;
}


// -------------------- Constructor --------------------
MedicalImageViewer::MedicalImageViewer() : Viewer("Medical Image Viewer") {
    // init view members
    frame = nullptr;
    frameLayout = nullptr;
    viewerMenu = nullptr;

    // view only 3D scene by default
    visibleLayout = VIEWER_3D;

    displayedTopLevelComponents = 0;

    autoUpdateToolbarVisibility = true;
}


// -------------------- Destructor --------------------
MedicalImageViewer::~MedicalImageViewer() {
    if (frame) {
        delete frame;
    }
}


// -------------------- numberOfViewedComponentgetWidget --------------------
unsigned int MedicalImageViewer::numberOfViewedComponent() {
    unsigned int count = 0;

    for (unsigned int i = 0; viewerVisibility[i] != VIEWER_ALL; i++) {
        count += viewers.value(viewerVisibility[i])->numberOfViewedComponent();
    }

    return count;
}

// -------------------- refresh --------------------
void MedicalImageViewer::refresh(Viewer* whoIsAsking) {
    // just tell everyone to update!
    foreach (Viewer* v, viewers.values()) {
        v->refresh(this);
    }

    // view everything?
    if (displayedTopLevelComponents != (unsigned) Application::getTopLevelComponents().size()) {
        // if there the nr of Component changed since last refresh,
        // and if there is something displayed in the slices viewer, show all view
        if (InteractiveViewer::getAxialViewer()->numberOfViewedComponent() > 0
                && InteractiveViewer::getCoronalViewer()->numberOfViewedComponent() > 0
                && InteractiveViewer::getSagittalViewer()->numberOfViewedComponent() > 0) {
            visibleLayout = VIEWER_ALL;
        }
        else {
            visibleLayout = VIEWER_3D;
        }

        updateLayout();

        // update the counter
        displayedTopLevelComponents = Application::getTopLevelComponents().size();
    }
}

// -------------------- getWidget --------------------
QWidget* MedicalImageViewer::getWidget(QWidget* parent) {
    if (!frame) {
        frame = new QFrame(parent);
        frame->setFrameStyle(QFrame::StyledPanel | QFrame::Plain);

        //-- init layout
        frameLayout = new QGridLayout(frame);
        frameLayout->setSpacing(0);
        frameLayout->setMargin(0);

        // gulp the enum
        viewerVisibility.append(VIEWER_3D);
        viewerVisibility.append(VIEWER_AXIAL);
        viewerVisibility.append(VIEWER_CORONAL);
        viewerVisibility.append(VIEWER_SAGITTAL);
        viewerVisibility.append(VIEWER_ARBITRARY); // ARBITRARY has to be before ALL
        viewerVisibility.append(VIEWER_ALL); // ALL has to be the end of visible viewers

        // list of viewer name
        viewers.insert(VIEWER_3D, InteractiveViewer::get3DViewer());
        viewers.insert(VIEWER_ARBITRARY, InteractiveViewer::getArbitraryViewer());
        viewers.insert(VIEWER_AXIAL, InteractiveViewer::getAxialViewer());
        viewers.insert(VIEWER_CORONAL, InteractiveViewer::getCoronalViewer());
        viewers.insert(VIEWER_SAGITTAL, InteractiveViewer::getSagittalViewer());

        //-- add the InteractiveViewers
//        topLeftLayout = new QVBoxLayout();
//        frameLayout->addLayout(topLeftLayout, 0, 0);
//        topLeftLayout->addWidget(InteractiveViewer::getAxialViewer()->getWidget(frame)); // north-west
//        topLeftLayout->addWidget(InteractiveViewer::getArbitraryViewer()->getWidget(frame)); // north-west
//        frameLayout->addWidget(InteractiveViewer::getCoronalViewer()->getWidget(frame), 0, 1); // north-east
//        frameLayout->addWidget(InteractiveViewer::getSagittalViewer()->getWidget(frame), 1, 0); // south-west
//        frameLayout->addWidget(InteractiveViewer::get3DViewer()->getWidget(frame), 1, 1); // south-east

        topLeftLayout = new QVBoxLayout();
        frameLayout->addLayout(topLeftLayout, 0, 0);
        topLeftLayout->addWidget(InteractiveViewer::getAxialViewer()->getWidget(frame));
//        frameLayout->addWidget(InteractiveViewer::getAxialViewer()->getWidget(frame), 0, 0); // north-west
        frameLayout->addWidget(InteractiveViewer::getCoronalViewer()->getWidget(frame), 1, 0); // north-east
        frameLayout->addWidget(InteractiveViewer::getSagittalViewer()->getWidget(frame), 1, 1); // south-west
        frameLayout->addWidget(InteractiveViewer::get3DViewer()->getWidget(frame), 0, 1); // south-east



        //-- connect
        foreach (LayoutVisibility v, viewerVisibility) {
            if (viewers.value(v)) { // prevent ALL
                connect(viewers.value(v), SIGNAL(selectionChanged()), this, SLOT(synchronizeSelection()));
            }
        }

        //-- show the correct viewer
        updateLayout();
    }

    return frame;
}

// ---------------------- getPropertyObject ----------------------------
QObject* MedicalImageViewer::getPropertyObject() {
    return InteractiveViewer::get3DViewer()->getPropertyObject();
}

// -------------------- getMenu --------------------
QMenu* MedicalImageViewer::getMenu() {
    if (!viewerMenu) {
        //-- create the main menu
        viewerMenu = new QMenu(objectName());
        viewerMenu->setTearOffEnabled(true);

        //-- build up menu
        QMenu* layoutMenu = new QMenu("Visible Viewers");
        viewerMenu->addMenu(layoutMenu);
        layoutMenu->addAction(Application::getAction("Show All Viewers")->getQAction());
        layoutMenu->addSeparator();

        //-- add the visibility action
        auto* viewerGroup = new QActionGroup(this);
        Application::getAction("Show All Viewers")->getQAction()->setActionGroup(viewerGroup);
        Application::getAction("Show 3D Viewer")->getQAction()->setActionGroup(viewerGroup);
        layoutMenu->addAction(Application::getAction("Show 3D Viewer")->getQAction());
        Application::getAction("Show Axial Viewer")->getQAction()->setActionGroup(viewerGroup);
        layoutMenu->addAction(Application::getAction("Show Axial Viewer")->getQAction());
        Application::getAction("Show Sagittal Viewer")->getQAction()->setActionGroup(viewerGroup);
        layoutMenu->addAction(Application::getAction("Show Sagittal Viewer")->getQAction());
        Application::getAction("Show Coronal Viewer")->getQAction()->setActionGroup(viewerGroup);
        layoutMenu->addAction(Application::getAction("Show Coronal Viewer")->getQAction());
        // disabled the arbitrary slice as long as it does not work correctly
        // Application::getAction("Show Arbitrary Viewer")->getQAction()->setActionGroup(viewerGroup);
        // layoutMenu->addAction(Application::getAction("Show Arbitrary Viewer")->getQAction());

        for (unsigned int i = 0; viewerVisibility[i] != VIEWER_ALL; i++) {
            // and viewer menu as submenu
            viewerMenu->addMenu(viewers.value(viewerVisibility[i])->getMenu());
        }

    }

    return viewerMenu;
}

// -------------------- getToolBar --------------------
QToolBar* MedicalImageViewer::getToolBar() {
    return viewers.value(VIEWER_3D)->getToolBar();
}


// -------------------- setVisibleViewer --------------------
void MedicalImageViewer::setVisibleViewer(LayoutVisibility visibleViewer) {

    visibleLayout = visibleViewer;

    updateLayout();
}

// -------------------- updateLayout --------------------
void MedicalImageViewer::updateLayout() {

    if (viewers.empty()) {
        return;
    }

    if (visibleLayout == VIEWER_ALL) {
        viewers.value(VIEWER_3D)->getWidget(frame)->show();
        viewers.value(VIEWER_AXIAL)->getWidget(frame)->show();
        viewers.value(VIEWER_CORONAL)->getWidget(frame)->show();
        viewers.value(VIEWER_SAGITTAL)->getWidget(frame)->show();
        viewers.value(VIEWER_ARBITRARY)->getWidget(frame)->hide();
    }
    else {
        for (unsigned int i = 0; viewerVisibility[i] != VIEWER_ALL; i++) {
            viewers.value(viewerVisibility[i])->getWidget(frame)->hide();
        }

        viewers.value(visibleLayout)->getWidget(frame)->show();
    }

    if (autoUpdateToolbarVisibility && (visibleLayout == VIEWER_3D || visibleLayout == VIEWER_ALL)) {
        getToolBar()->show();
    }

}

// -------------------- synchronizeSelection --------------------
void MedicalImageViewer::synchronizeSelection() {
    auto* whoIsAsking = qobject_cast<Viewer*>(sender());

    foreach (Viewer* v, viewers.values()) {
        if (v != whoIsAsking) {
            v->refresh(whoIsAsking);
        }
    }

    // lets inform the extern viewers that there was a modification
    emit selectionChanged();
}

// -------------------- setToolbarAutoVisibility --------------------
void MedicalImageViewer::setToolbarAutoVisibility(bool toolbarVisibility) {
    autoUpdateToolbarVisibility = toolbarVisibility;
    getToolBar()->setVisible(autoUpdateToolbarVisibility);
    if (!autoUpdateToolbarVisibility) {
        getToolBar()->close();
    }
}

}

