#include <QtGui>
#include <cmath>

#include "plotter.h"
#include "graph.h"
#include "fcan_view.h"

Plotter::Plotter(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	hide();

	setWindowTitle("Plotter(Graph)");

	pFcanView = NULL;
	pGraph = NULL;
	pPlotSettings = NULL;

	MarginX = 50;
	GraphCount = 0;
	TimeMode = 0;
    ui.lblGraph->hide();

    setBackgroundRole(QPalette::Dark);
    setAutoFillBackground(true);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setFocusPolicy(Qt::StrongFocus);
    rubberBandIsShown = false;

    lblZoom = new QLabel(this);
	lblZoom->setText("Zoom: 1.00");
    lblZoom->adjustSize();
//  lblZoom->setEnabled(true);
//  lblZoom->show();

    zoomInButton = new QToolButton(this);
//  zoomInButton->setIcon(QIcon(":/images/zoomin.png"));
    zoomInButton->setIcon(QIcon("./images/zoomin.png"));
    zoomInButton->adjustSize();
    connect(zoomInButton, SIGNAL(clicked()), this, SLOT(zoomIn()));

    zoomOutButton = new QToolButton(this);
//  zoomOutButton->setIcon(QIcon(":/images/zoomout.png"));
    zoomOutButton->setIcon(QIcon("./images/zoomout.png"));
    zoomOutButton->adjustSize();
    connect(zoomOutButton, SIGNAL(clicked()), this, SLOT(zoomOut()));

    setPlotSettings(PlotSettings());

	// Menu Init
	createMenus();

//	ui.menuBar->setStyleSheet("background-color : rgb(230,230,230);");

}

Plotter::~Plotter()
{

}

////////////////////////////////////////
// Pointer Setting
////////////////////////////////////////
void Plotter::FcanViewSet( FCAN_View * fcanview )
{
	pFcanView = fcanview;
}
void Plotter::GraphSet( Graph * graph )
{
	pGraph = graph;
}
void Plotter::PlotSettingsSet( PlotSettings * plotsettings )
{
	pPlotSettings = plotsettings;
}
////////////////////////////////////////
// Plotter Function
////////////////////////////////////////
void Plotter::PlotterStart()
{
    zoomStack.clear();
    zoomStack.append(*pPlotSettings);
    curZoom = 0;
    zoomInButton->hide();
    zoomOutButton->hide();
    lblZoom->hide();
    ui.lblGraph->hide();
    refreshPixmap();

	Graph1Yaxis = 0;
	GraphCount = 0;
	for( int i = 0; i < 5; i=i+1 ){
		if( pGraph->GraphWindow[i] == true
			&& pGraph->GraphYaxisSelect[i] == 0 ){
			GraphCount = GraphCount + 1;
		}
	}
	for( int i = 1; i < 5; i=i+1 ){
		if( pGraph->GraphWindow[i] == true
			&& pGraph->GraphYaxisSelect[i] == 1 ){
			Graph1Yaxis = 1;
		}
	}
//	if( Graph1Yaxis == 0 ){
//		GraphCount = GraphCount - 1;
//	}

//	MarginX = Margin + (( GraphCount - 1 ) * Margin );
	MarginX = Margin + ( GraphCount * Margin );

}
void Plotter::closeEvent(QCloseEvent * pEvent)
{
	pGraph->GraphWindowOpen = 0;
	pGraph->close();

}
void Plotter::PlotterRighView()
{
	zoomStack[curZoom].scroll(+1, 0);
	refreshPixmap();
}
void Plotter::setPlotSettings(const PlotSettings &settings)
{
    zoomStack.clear();
    zoomStack.append(settings);
    curZoom = 0;
    zoomInButton->hide();
    zoomOutButton->hide();
    lblZoom->hide();
    refreshPixmap();
}

void Plotter::zoomOut()
{
    if (curZoom > 0) {
        --curZoom;
        zoomOutButton->setEnabled(curZoom > 0);
        zoomInButton->setEnabled(true);
        zoomInButton->show();
//	    lblZoom->setEnabled(true);
//	    lblZoom->show();
        refreshPixmap();
    }
}

void Plotter::zoomIn()
{
    if (curZoom < zoomStack.count() - 1) {
        ++curZoom;
        zoomInButton->setEnabled(curZoom < zoomStack.count() - 1);
        zoomOutButton->setEnabled(true);
        zoomOutButton->show();
//	    lblZoom->setEnabled(true);
//	    lblZoom->show();
        refreshPixmap();
    }
}

void Plotter::setCurveData(int id, const QVector<QPointF> &data)
{
    curveMap[id] = data;
    refreshPixmap();
}

void Plotter::clearCurve(int id)
{
    curveMap.remove(id);
    refreshPixmap();
}

QSize Plotter::minimumSizeHint() const
{
    return QSize((MarginX + (5 * Margin)), (MarginH + (3 * Margin)));
}

QSize Plotter::sizeHint() const
{
    return QSize((MarginX + (11 * Margin)), (MarginH + (7 * Margin)));
}

void Plotter::paintEvent(QPaintEvent * /* event */)
{
    QStylePainter painter(this);
    painter.drawPixmap(0, 0, pixmap);

    if (rubberBandIsShown) {
        painter.setPen(palette().light().color());
        painter.drawRect(rubberBandRect.normalized()
                                       .adjusted(0, 0, -1, -1));
    }

    if (hasFocus()) {
        QStyleOptionFocusRect option;
        option.initFrom(this);
        option.backgroundColor = palette().dark().color();
        painter.drawPrimitive(QStyle::PE_FrameFocusRect, option);
    }
}

void Plotter::resizeEvent(QResizeEvent * /* event */)
{
//  int x = width() - (zoomInButton->width()
//                     + zoomOutButton->width() + 10);
//  zoomInButton->move(x, 5);
//  zoomOutButton->move(x + zoomInButton->width() + 5, 5);

    int x = width() - (lblZoom->width() + zoomInButton->width()
                       + zoomOutButton->width() + 15);
    lblZoom->move(x, 30);
    zoomInButton->move(x + lblZoom->width() + 5, 28);
    zoomOutButton->move(x + lblZoom->width() + zoomInButton->width() + 10, 28);

    refreshPixmap();
}

void Plotter::mousePressEvent(QMouseEvent *event)
{
    QRect rect(MarginX, MarginH,
               width() - MarginX - Margin, height() - MarginH - Margin);

    if (event->button() == Qt::LeftButton) {
        if (rect.contains(event->pos())) {
            rubberBandIsShown = true;
            rubberBandRect.setTopLeft(event->pos());
            rubberBandRect.setBottomRight(event->pos());
            updateRubberBandRegion();
            setCursor(Qt::CrossCursor);
        }
    }
}

void Plotter::mouseMoveEvent(QMouseEvent *event)
{
    if (rubberBandIsShown) {
        updateRubberBandRegion();
        rubberBandRect.setBottomRight(event->pos());
        updateRubberBandRegion();
    }
}

void Plotter::mouseReleaseEvent(QMouseEvent *event)
{
	double dx;
	double dy[6];

    if ((event->button() == Qt::LeftButton) && rubberBandIsShown) {
        rubberBandIsShown = false;
        updateRubberBandRegion();
        unsetCursor();

        QRect rect = rubberBandRect.normalized();
        if (rect.width() < 4 || rect.height() < 4)
            return;
        rect.translate(-MarginX, -Margin);

        PlotSettings prevSettings = zoomStack[curZoom];
        PlotSettings settings;
        dx = prevSettings.spanX() / (width() - MarginX - Margin);
        dy[1] = prevSettings.spanY1() / (height() - MarginH - Margin);
        dy[2] = prevSettings.spanY2() / (height() - MarginH - Margin);
        dy[3] = prevSettings.spanY3() / (height() - MarginH - Margin);
        dy[4] = prevSettings.spanY4() / (height() - MarginH - Margin);
        dy[5] = prevSettings.spanY5() / (height() - MarginH - Margin);
        settings.minX = prevSettings.minX + dx * rect.left();
        settings.maxX = prevSettings.minX + dx * rect.right();
		for ( int i = 1; i < 6; i=i+1 ){
			settings.minY[i] = prevSettings.maxY[i] - dy[i] * rect.bottom();
			settings.maxY[i] = prevSettings.maxY[i] - dy[i] * rect.top();
		}
        settings.adjust();
		settings.zoomSize = ( prevSettings.spanX() / settings.spanX() )
							 * ( prevSettings.spanY1() / settings.spanY1() )
							 * prevSettings.zoomSize;
        zoomStack.resize(curZoom + 1);
        zoomStack.append(settings);
        zoomIn();
    }
}

void Plotter::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Plus:
        zoomIn();
        break;
    case Qt::Key_Minus:
        zoomOut();
        break;
    case Qt::Key_Left:
        zoomStack[curZoom].scroll(-1, 0);
        refreshPixmap();
        break;
    case Qt::Key_Right:
        zoomStack[curZoom].scroll(+1, 0);
        refreshPixmap();
        break;
    case Qt::Key_Down:
        zoomStack[curZoom].scroll(0, -1);
        refreshPixmap();
        break;
    case Qt::Key_Up:
        zoomStack[curZoom].scroll(0, +1);
        refreshPixmap();
        break;
	case Qt::Key_End:
	    EndScroll();
        break;
    default:
        QWidget::keyPressEvent(event);
    }
}

void Plotter::wheelEvent(QWheelEvent *event)
{
    int numDegrees = event->delta() / 8;
    int numTicks = numDegrees / 15;

    if (event->orientation() == Qt::Horizontal) {
        zoomStack[curZoom].scroll(numTicks, 0);
    } else {
        zoomStack[curZoom].scroll(0, numTicks);
    }
    refreshPixmap();
}

void Plotter::updateRubberBandRegion()
{
    QRect rect = rubberBandRect.normalized();
    update(rect.left(), rect.top(), rect.width(), 1);
    update(rect.left(), rect.top(), 1, rect.height());
    update(rect.left(), rect.bottom(), rect.width(), 1);
    update(rect.right(), rect.top(), 1, rect.height());
}

void Plotter::refreshPixmap()
{
    pixmap = QPixmap(size());
    pixmap.fill(this, 0, 0);

    QPainter painter(&pixmap);
    painter.initFrom(this);
    drawGrid(&painter);
    drawCurves(&painter);
    update();

//	ui.menuBar->setStyleSheet("background-color : rgb(230,230,230);");
}

void Plotter::drawGrid(QPainter *painter)
{
	int GraphViewCount;
	int GraphYaxisCount;
	int name_x;
	int name_y;
	double spanY;
	QString qt_str;
    static const QColor colorForText[6] = {
        Qt::red, Qt::green, Qt::blue, Qt::cyan, Qt::magenta, Qt::yellow
    };
    QRect rect(MarginX, MarginH,
               width() - MarginX - Margin, height() - MarginH - Margin);
    if (!rect.isValid())
        return;

    PlotSettings settings = zoomStack[curZoom];
    QPen quiteDark = palette().dark().color().light();
    QPen light = palette().light().color();

	qt_str.sprintf("Zoom: %.2f", settings.zoomSize);
	lblZoom->setText(qt_str);
    lblZoom->adjustSize();
	int pos_x = width() - (lblZoom->width() + zoomInButton->width()
							+ zoomOutButton->width() + 15);
	lblZoom->move(pos_x, 30);

	painter->setPen(light);
	painter->drawText(pos_x, 30, lblZoom->width(), 15,
						Qt::AlignHCenter | Qt::AlignTop,
						qt_str);

    for (int i = 0; i <= settings.numXTicks; ++i) {
        int x = rect.left() + (i * (rect.width() - 1)
                                 / settings.numXTicks);
        double label = settings.minX + (i * settings.spanX()
                                          / settings.numXTicks);
		qt_str = TimeCalc(label);
        painter->setPen(quiteDark);
        painter->drawLine(x, rect.top(), x, rect.bottom());
        painter->setPen(light);
        painter->drawLine(x, rect.bottom(), x, rect.bottom() + 5);
        painter->drawText(x - 50, rect.bottom() + 5, 100, 15,
                          Qt::AlignHCenter | Qt::AlignTop,
                          qt_str);
		if( i == settings.numXTicks ){
			if( TimeMode == 0 ){
				qt_str = "SS";
			} else if( TimeMode == 1 ){
				qt_str = "MM:SS";
			} else {
				qt_str = "HH:MM:SS";
			}
			painter->drawText(rect.right() - 50, rect.bottom() + 25, 100, 15,
								Qt::AlignHCenter | Qt::AlignTop,
	                        	qt_str);
		}
    }

	GraphViewCount = 0;
	GraphYaxisCount = 0;
	if( pGraph != NULL ){
		for( int lp=0; lp<5; lp=lp+1 ){
			if( lp == 0 )       { spanY = settings.spanY1();
			} else if( lp == 1 ){ spanY = settings.spanY2();
			} else if( lp == 2 ){ spanY = settings.spanY3();
			} else if( lp == 3 ){ spanY = settings.spanY4();
			} else              { spanY = settings.spanY5();
			}
			if( pGraph->GraphWindow[lp] == true ){
				for (int j = 0; j <= settings.numYTicks; ++j) {
					if( pGraph->GraphYaxisSelect[lp] == 0 ){
						int y = rect.bottom() - (j * (rect.height() - 1)
													/ settings.numYTicks);
						double label = settings.minY[lp+1] + (j * spanY / settings.numYTicks);
						painter->setPen(quiteDark);
						painter->drawLine(rect.left(), y, rect.right(), y);


						painter->setPen(light);
						painter->drawLine(rect.left() - ( Margin * GraphYaxisCount ) - 5, y,
											rect.left() - ( Margin * GraphYaxisCount ), y);

						painter->drawLine(rect.left() - ( Margin * GraphYaxisCount ), rect.top(),
										  rect.left() - ( Margin * GraphYaxisCount ), rect.bottom());

						painter->drawText(rect.left() - Margin - ( Margin * GraphYaxisCount ), y - 10, Margin - 5, 15,
											Qt::AlignRight | Qt::AlignVCenter,
											QString::number(label));


						if( pGraph->pGraphItem[lp] != NULL ){
							painter->setPen(colorForText[lp]);
							qt_str = pGraph->pGraphItem[lp]->denomination;
							painter->drawText(rect.left() - Margin - ( Margin * GraphYaxisCount ), rect.bottom() + 5,
												Margin - 5, 15,
												Qt::AlignHCenter | Qt::AlignTop,
												qt_str);
							qt_str.sprintf("CH%d", GraphViewCount+1);
							painter->drawText(rect.left() - Margin - ( Margin * GraphYaxisCount ), rect.bottom() + 20,
												Margin - 5, 15,
												Qt::AlignHCenter | Qt::AlignTop,
												qt_str);
							painter->setPen(light);
						}
					} else {
						int y = rect.bottom() - (j * (rect.height() - 1)
													/ settings.numYTicks);
						double label = settings.minY[lp+1] + (j * spanY / settings.numYTicks);
						painter->setPen(quiteDark);
						painter->drawLine(rect.left(), y, rect.right(), y);
						painter->setPen(light);
						painter->drawLine(rect.left() - 5, y, rect.left(), y);
						painter->drawText(rect.left() - Margin, y - 10, Margin - 5, 15,
											Qt::AlignRight | Qt::AlignVCenter,
											QString::number(label));
						if( lp == 0 && Graph1Yaxis == 0 && pGraph->pGraphItem[lp] != NULL ){
							painter->setPen(colorForText[lp]);
							qt_str = pGraph->pGraphItem[lp]->denomination;
							painter->drawText(rect.left() - Margin - ( Margin * GraphYaxisCount ), rect.bottom() + 5,
												Margin - 5, 15,
												Qt::AlignHCenter | Qt::AlignTop,
												qt_str);
							qt_str.sprintf("CH%d", GraphViewCount+1);
							painter->drawText(rect.left() - Margin - ( Margin * GraphYaxisCount ), rect.bottom() + 20,
												Margin - 5, 15,
												Qt::AlignHCenter | Qt::AlignTop,
												qt_str);
							painter->setPen(light);



						}
					}
				}
				if( pGraph->pGraphItem[lp] != NULL ){
					painter->setPen(colorForText[lp]);
					if( GraphViewCount == 0 )       { qt_str = pGraph->pGraphItem[lp]->name; name_x = MarginX;     name_y = 28;
					} else if( GraphViewCount == 1 ){ qt_str = pGraph->pGraphItem[lp]->name; name_x = MarginX+90;  name_y = 28;
					} else if( GraphViewCount == 2 ){ qt_str = pGraph->pGraphItem[lp]->name; name_x = MarginX+180; name_y = 28;
					} else if( GraphViewCount == 3 ){ qt_str = pGraph->pGraphItem[lp]->name; name_x = MarginX;     name_y = 43;
					} else                          { qt_str = pGraph->pGraphItem[lp]->name; name_x = MarginX+90;  name_y = 43;
					}
					painter->drawText(name_x, name_y,
									80, 15,
									Qt::AlignLeft | Qt::AlignTop,
									qt_str);
					painter->setPen(light);
				}
				GraphViewCount = GraphViewCount + 1;
				if( pGraph->GraphYaxisSelect[lp] == 0 ){
					GraphYaxisCount = GraphYaxisCount + 1;
				} else if( pGraph->GraphYaxisSelect[lp] == 1 ){
					if( lp == 0 ){
						GraphYaxisCount = GraphYaxisCount + 1;
					}
				}
			} else if( pGraph->GraphWindow[lp] != true && Graph1Yaxis == 1 ){
				if( lp == 0 ){
					for (int j = 0; j <= settings.numYTicks; ++j) {
						int y = rect.bottom() - (j * (rect.height() - 1)
													/ settings.numYTicks);
						double label = settings.minY[lp+1] + (j * spanY / settings.numYTicks);
						painter->setPen(quiteDark);
						painter->drawLine(rect.left(), y, rect.right(), y);
						painter->setPen(light);
						painter->drawLine(rect.left() - 5, y, rect.left(), y);
						painter->drawText(rect.left() - MarginX, y - 10, MarginX - 5, 15,
											Qt::AlignRight | Qt::AlignVCenter,
											QString::number(label));
					}
					GraphYaxisCount = GraphYaxisCount + 1;
				}
			} else {
				if( pGraph->GraphWindow[0] != true
					&& pGraph->GraphWindow[1] != true
					&& pGraph->GraphWindow[2] != true
					&& pGraph->GraphWindow[3] != true
					&& pGraph->GraphWindow[4] != true ){

					for (int j = 0; j <= settings.numYTicks; ++j) {
						int y = rect.bottom() - (j * (rect.height() - 1)
													/ settings.numYTicks);
						double label = settings.minY[lp+1] + (j * spanY / settings.numYTicks);
						painter->setPen(quiteDark);
						painter->drawLine(rect.left(), y, rect.right(), y);
						painter->setPen(light);
						painter->drawLine(rect.left() - 5, y, rect.left(), y);
						painter->drawText(rect.left() - MarginX, y - 10, MarginX - 5, 15,
											Qt::AlignRight | Qt::AlignVCenter,
											QString::number(label));
					}
				}
			}
		}
	} else {
		for (int j = 0; j <= settings.numYTicks; ++j) {
			int y = rect.bottom() - (j * (rect.height() - 1)
										/ settings.numYTicks);
			double label = settings.minY[1] + (j * settings.spanY1() / settings.numYTicks);
			painter->setPen(quiteDark);
			painter->drawLine(rect.left(), y, rect.right(), y);
			painter->setPen(light);
			painter->drawLine(rect.left() - 5, y, rect.left(), y);
			painter->drawText(rect.left() - MarginX, y - 10, MarginX - 5, 15,
								Qt::AlignRight | Qt::AlignVCenter,
								QString::number(label));
		}
	}

    painter->drawRect(rect.adjusted(0, 0, -1, -1));

}

void Plotter::drawCurves(QPainter *painter)
{
	double spanY;
    static const QColor colorForIds[6] = {
        Qt::red, Qt::green, Qt::blue, Qt::cyan, Qt::magenta, Qt::yellow
    };

    PlotSettings settings = zoomStack[curZoom];
    QRect rect(MarginX, MarginH,
               width() - MarginX - Margin, height() - MarginH - Margin);
    if (!rect.isValid())
        return;

    painter->setClipRect(rect.adjusted(+1, +1, -1, -1));

    QMapIterator<int, QVector<QPointF> > i(curveMap);
    while (i.hasNext())
	{
        i.next();

        int id = i.key();
        const QVector<QPointF> &data = i.value();
        QPolygonF polyline(data.count());

		painter->setPen(colorForIds[uint(id) % 6]);

		if( id == 0 )       { spanY = settings.spanY1();
		} else if( id == 1 ){ spanY = settings.spanY2();
		} else if( id == 2 ){ spanY = settings.spanY3();
		} else if( id == 3 ){ spanY = settings.spanY4();
		} else              { spanY = settings.spanY5();
		}

        for (int j = 0; j < data.count(); ++j) {
            double dx = data[j].x() - settings.minX;
            double dy = data[j].y() - settings.minY[id+1];
            double x = rect.left() + (dx * (rect.width() - 1)
                                         / settings.spanX());
            double y = rect.bottom() - (dy * (rect.height() - 1) / spanY);
            polyline[j] = QPointF(x, y);

//			painter->drawLine( QPoint( x-10, y-10 ), QPoint(x+10, y+10) );
//			painter->drawLine( QPoint( x+10, y-10 ), QPoint(x-10, y+10) );
			painter->drawLine( QPoint( x-2, y-2 ), QPoint(x+2, y+2) );
			painter->drawLine( QPoint( x+2, y-2 ), QPoint(x-2, y+2) );

		}
        painter->drawPolyline(polyline);
    }
}

void Plotter::GraphNameSet()
{
	QString qt_str;

	qt_str = "Plotter(" + pGraph->GraphName + ")";
	setWindowTitle(qt_str);

}

QString Plotter::TimeCalc(double time)
{
	int t_tmp;
	double t_millis;
	int t_sec;
	int t_min;
	int t_hour;
	double time_abs;
	double time_tmp;
	QString qt_str;
	QString time_abs_str;
	QString time_str;

	if( time < 0 ){
		time_abs = abs(time);
		time_abs_str = "-";
	} else {
		time_abs = time;
		time_abs_str = "";
	}

	// millis
	t_tmp = time_abs;
	t_millis = time_abs - (double)t_tmp;
	// second
	t_sec = t_tmp % 60;
	t_tmp = t_tmp / 60;
	// minute
	t_min = t_tmp % 60;
	t_tmp = t_tmp / 60;
	// hour
	t_hour = t_tmp % 60;
	t_tmp = t_tmp / 60;

	TimeMode = 0;

	if( t_hour != 0 ){
		time_str = qt_str.sprintf("%d:", t_hour);
	}
	if( t_hour == 0 ){
		if( t_min != 0 ){
			time_str = qt_str.sprintf("%d:", t_min);
			TimeMode = 1;
		} else {
			time_str = "";
			TimeMode = 0;
		}
	} else {
		time_str = time_str + qt_str.sprintf("%02d:", t_min);
		TimeMode = 2;
	}
	if( t_sec < 10 && ( t_hour != 0 || t_min != 0 )){
		time_str = time_str + qt_str.sprintf("0%g", (t_sec + t_millis));
	} else {
		time_str = time_str + qt_str.sprintf("%g", (t_sec + t_millis));
	}

	time_str = time_abs_str + time_str;

	return time_str;

}

void Plotter::EndScroll( )
{

	int scrollcount;
	double numspanX;
	double maxtime;
    PlotSettings settings = zoomStack[curZoom];

	maxtime = pGraph->EndScroll();
	if( maxtime != 0 ){
		numspanX = settings.spanX() / settings.numXTicks;
		maxtime = ( maxtime / 1000 ) - settings.minX;
		scrollcount = int( maxtime / numspanX ) - 3;
	} else {
		scrollcount = 0;
	}
	zoomStack[curZoom].scroll(scrollcount, 0);
	refreshPixmap();

}

////////////////////////////////////////
// Setting Menu
////////////////////////////////////////
void Plotter::createMenus()
{
	QMenu   * pMenu_Setting;
	QMenu   * pMenu_Graph;

	//Setting Menu
	pMenu_Setting = ui.menuBar->addMenu( tr("Graph") );
	SettingMenu.pMenu = pMenu_Setting;
    connect(pMenu_Setting, SIGNAL(aboutToShow()), this, SLOT(menu_triggered()));

	//Graph Menu
	pMenu_Graph = ui.menuBar->addMenu( tr("Control") );
	GraphMenu.pMenu = pMenu_Graph;
    connect(pMenu_Graph, SIGNAL(aboutToShow()), this, SLOT(menu_triggered()));

	createMenuActions();

}
void Plotter::createMenuActions()
{
	QAction * pAction;
	QString qt_str;

	/* Clear */
	SettingMenu.pMenu->clear( );
	
	/* Load File */
	pAction = new QAction( tr("Setting"), this );
	pAction->setShortcut(tr("Ctrl+S"));
	SettingMenu.pSetting = pAction;
	SettingMenu.pMenu->addAction( pAction );
    connect(pAction, SIGNAL(triggered()), this, SLOT(menu_setting()));

	/* Print */
	pAction = new QAction( tr("Print"), this );
	pAction->setShortcut(tr("Ctrl+P"));
	SettingMenu.pPrint = pAction;
	SettingMenu.pMenu->addAction( pAction );
    connect(pAction, SIGNAL(triggered()), this, SLOT(menu_print()));


	/* Clear */
	GraphMenu.pMenu->clear( );
	
	/* StartStop */
	pAction = new QAction( tr("StartStop"), this );
	pAction->setShortcut(tr("Ctrl+B"));
	GraphMenu.pStartStop = pAction;
	GraphMenu.pMenu->addAction( pAction );
	connect(pAction, SIGNAL(triggered()), this, SLOT(menu_startstop()));

	/* ViewEndPoint */
	pAction = new QAction( tr("ViewEndPoint"), this );
	pAction->setShortcut(tr("Ctrl+E"));
	GraphMenu.pViewEndPoint = pAction;
	GraphMenu.pMenu->addAction( pAction );
	connect(pAction, SIGNAL(triggered()), this, SLOT(menu_viewendpoint()));

}

////////////////////////////////////////
// Menu Action
////////////////////////////////////////
void Plotter::menu_triggered()
{
	createMenuActions();
}
void Plotter::menu_setting()
{

	pGraph->GraphWindowOpen = 1;
	pFcanView->GraphViewShow(pGraph->GraphNumber);

}
void Plotter::menu_startstop()
{

	QString qt_ret;
	QMessageBox msgBox;

	if( pGraph->GraphReciveMode == 1 ){
		pGraph->GraphStartStop();
	} else {
		msgBox.setText("Can not Graph File Load Mode !");
		qt_ret = msgBox.exec();
	}

}
void Plotter::menu_viewendpoint()
{
	    EndScroll();
}
void Plotter::menu_print()
{

	QPrinter printer;
	QPrintDialog printDialog(&printer, this);
	if( printDialog.exec()){
		QPainter painter(&printer);
		QRect rect = painter.viewport();
		QSize size = pixmap.size();
		size.scale(rect.size(),Qt::KeepAspectRatio);
		painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
		painter.setWindow(pixmap.rect());
		painter.drawPixmap(0, 0, pixmap);
	}

}

////////////////////////////////////////
// PlotSettings Function
////////////////////////////////////////
PlotSettings::PlotSettings()
{
    minX = 0.0;
    maxX = 10.0;
    numXTicks = 5;
	for( int i = 1; i < 6; i=i+1 ){
		minY[i] = 0.0;
		maxY[i] = 10.0;
	}
    numYTicks = 5;
    zoomSize = 1.0;
}

void PlotSettings::scroll(int dx, int dy)
{
    double stepY[6];

    double stepX = spanX() / numXTicks;
    minX += dx * stepX;
    maxX += dx * stepX;

    stepY[1] = spanY1() / numYTicks;
    stepY[2] = spanY2() / numYTicks;
    stepY[3] = spanY3() / numYTicks;
    stepY[4] = spanY4() / numYTicks;
    stepY[5] = spanY5() / numYTicks;
	for( int i = 0; i < 6; i=i+1 ){
		minY[i] += dy * stepY[i];
		maxY[i] += dy * stepY[i];
	}
}

void PlotSettings::adjust()
{
    adjustAxis(minX, maxX, numXTicks);
	for( int i = 1; i < 6; i=i+1 ){
		adjustAxis(minY[i], maxY[i], numYTicks);
	}
}

void PlotSettings::adjustAxis(double &min, double &max,
                              int &numTicks)
{
    const int MinTicks = 4;
    double grossStep = (max - min) / MinTicks;
    double step = pow(10.0, floor(log10(grossStep)));

    if (5 * step < grossStep) {
        step *= 5;
    } else if (2 * step < grossStep) {
        step *= 2;
    }

    numTicks = int(ceil(max / step) - floor(min / step));
    if (numTicks < MinTicks)
        numTicks = MinTicks;
    min = floor(min / step) * step;
    max = ceil(max / step) * step;
}

