#include "plot.h"
#include <QFile>
#include <fstream>
#include <QMessageBox>
plot::plot(QWidget *parent):QwtPlot(parent)
{
    //初始化类中的变量
    setTitle("sesmic wave ");
    filename="";
    divconst=20000;
    number_of_trace=0;
    trace_length=0;
    trace_long=0;
    //画布初始化
    setCanvasBackground(Qt::white);
    enableAxis(QwtPlot::xTop,true);
    enableAxis(QwtPlot::xBottom,false);
    setAxisScale(QwtPlot::yLeft,1250.0,0.0);          //暂时将坐标轴定义为1250*240的,后面需要再进行改变
    setAxisScale(QwtPlot::xTop,0.0,240);
    //connection
    connect(this,SIGNAL(haveData()),this,SLOT(dataShow()));
    resize(QSize(700,700));
}
bool plot::doOpen(const QString & filename_temp,const int &number_of_trace_temp,const int &tracelength_temp,const int &trace_long_temp)
{
//    if(sizeof(temp_curve)>sizeof(QwtPlotCurve))delete []temp_curve;
  //  if(sizeof(container)>sizeof(QPolygonF))delete []container;
    filename=filename_temp;
    number_of_trace=number_of_trace_temp;
    trace_length=tracelength_temp;
    trace_long=trace_long_temp;
    //if(!filename.endsWith(".sgy"))DIALOG_1
    std::ifstream fin;
    //DIALOG_2
    QByteArray temp_array =filename.toLocal8Bit();
    fin.open(temp_array.data(),std::ios::in);
    assert(fin);
//c++方式打开文件
//container 是指向QPloygonF的指针
    container = new QPolygonF[trace_length];
    for(int i=0;i<trace_length;i++)
    {
        for(int j=0;j<trace_long;j++)
        {
            float temp(0);
            fin.seekg(3840+(1250*4+240)*i+j*4);
            fin.read(reinterpret_cast<char *>(&temp),sizeof(temp));
            temp=fourbytechange(temp);
            *(container+i)<<QPointF(temp/divconst+i,j);
        }
     }
    fin.close();
    emit haveData();
    return 0;
}
void plot::dataShow()
{
    //DIALOG_filename
    setAxisScale(QwtPlot::yLeft,trace_long,0);
    setAxisScale(QwtPlot::xTop,0,trace_length);
    temp_curve  = new QwtPlotCurve[trace_length];
    for(int i=0;i<trace_length;i++)
    {
        (temp_curve+i)->setPen(QPen(Qt::blue,1));
        (temp_curve+i)->setRenderHint(QwtPlotItem::RenderAntialiased,true);
        (temp_curve+i)->setSamples(*(container+i));
        (temp_curve+i)->setXAxis(QwtPlot::xTop);
        (temp_curve+i)->setYAxis(QwtPlot::yLeft);
        (temp_curve+i)->attach(this);
        replot();
    }
}
plot::~plot()
{
    delete []temp_curve;
    delete []container;
}
float plot::fourbytechange(float num)
{
    union{float big;char small[4];}a,b;
    a.big=num;
    b.big=num;
    b.small[0]=a.small[3];
    b.small[1]=a.small[2];
    b.small[2]=a.small[1];
    b.small[3]=a.small[0];
    return b.big;
}