#include "SatelliteGF3xmlParser.h"
#include <QDateTime>


bool SatelliteGF3xmlParser::loadFile(const QString& filename) {
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << u8"Cannot open file:" << filename;
        return false;
    }

    QDomDocument doc;
    if (!doc.setContent(&file)) {
        file.close();
        qWarning() << u8"Failed to parse the file into a DOM tree.";
        return false;
    }
    file.close();

    xml = doc;

    this->parseAdditionalData();
    this->parseImageInfo();
    this->parsePlatform();
    this->parseGPS();

    //处理时间
    double tempreftime = start + (end - start) / 2;
	for (long i = 0;i < antposs.size();i++)
	{
		antposs[i].time = antposs[i].time - tempreftime;
	}

    start = start- tempreftime;
	end = end- tempreftime;


    return true;
}

void SatelliteGF3xmlParser::parsePlatform() {
    QDomElement platform = xml.firstChildElement("product").firstChildElement("platform");
    if (!platform.isNull()) {
        CenterTime = platform.firstChildElement("CenterTime").text();
        Rs = platform.firstChildElement("Rs").text().toDouble();
        satVelocity = platform.firstChildElement("satVelocity").text().toDouble();
        RollAngle = platform.firstChildElement("RollAngle").text().toDouble();
        PitchAngle = platform.firstChildElement("PitchAngle").text().toDouble();
        YawAngle = platform.firstChildElement("YawAngle").text().toDouble();
        Xs = platform.firstChildElement("Xs").text().toDouble();
        Ys = platform.firstChildElement("Ys").text().toDouble();
        Zs = platform.firstChildElement("Zs").text().toDouble();
        Vxs = platform.firstChildElement("Vxs").text().toDouble();
        Vys = platform.firstChildElement("Vys").text().toDouble();
        Vzs = platform.firstChildElement("Vzs").text().toDouble();

        qDebug() << u8"Platform Data:";
        qDebug() << u8"CenterTime:" << CenterTime;
        qDebug() << u8"Rs:" << Rs;
        qDebug() << u8"satVelocity:" << satVelocity;
        qDebug() << u8"RollAngle:" << RollAngle;
        qDebug() << u8"PitchAngle:" << PitchAngle;
        qDebug() << u8"YawAngle:" << YawAngle;
        qDebug() << u8"Xs:" << Xs;
        qDebug() << u8"Ys:" << Ys;
        qDebug() << u8"Zs:" << Zs;
        qDebug() << u8"Vxs:" << Vxs;
        qDebug() << u8"Vys:" << Vys;
        qDebug() << u8"Vzs:" << Vzs;
    }
}

void SatelliteGF3xmlParser::parseGPS() {
    QDomElement GPS = xml.firstChildElement("product").firstChildElement("GPS");
    if (!GPS.isNull()) {
        QDomNodeList GPSParams = GPS.elementsByTagName("GPSParam");
        for (int i = 0; i < GPSParams.count(); ++i) {
            QDomElement GPSParam = GPSParams.at(i).toElement();
            SatellitePos satepos{0.0 ,0.0,0.0,0.0, 0.0,0.0,0.0 };

            QString TimeStamp = GPSParam.firstChildElement("TimeStamp").text();
            QString xPosition = GPSParam.firstChildElement("xPosition").text();
            QString yPosition = GPSParam.firstChildElement("yPosition").text();
            QString zPosition = GPSParam.firstChildElement("zPosition").text();
            QString xVelocity = GPSParam.firstChildElement("xVelocity").text();
            QString yVelocity = GPSParam.firstChildElement("yVelocity").text();
            QString zVelocity = GPSParam.firstChildElement("zVelocity").text();

           
            TimestampMicroseconds dateTime = parseAndConvert(TimeStamp.toStdString());
			satepos.time = dateTime.msecsSinceEpoch / 1000.0 + dateTime.microseconds / 100000.0;
			satepos.Px = xPosition.toDouble();
			satepos.Py = yPosition.toDouble();
			satepos.Pz = zPosition.toDouble();
			satepos.Vx = xVelocity.toDouble();
			satepos.Vy = yVelocity.toDouble();
			satepos.Vz = zVelocity.toDouble();

            this->antposs.append(satepos);

            qDebug() << u8"\nGPS Param Data:";
            qDebug() << u8"TimeStamp:" << TimeStamp;
            qDebug() << u8"xPosition:" << xPosition;
            qDebug() << u8"yPosition:" << yPosition;
            qDebug() << u8"zPosition:" << zPosition;
            qDebug() << u8"xVelocity:" << xVelocity;
            qDebug() << u8"yVelocity:" << yVelocity;
            qDebug() << u8"zVelocity:" << zVelocity;
        }
    }
}

void SatelliteGF3xmlParser::parseImageInfo() {
    QDomElement imageinfo = xml.firstChildElement("product").firstChildElement("imageinfo");
    if (!imageinfo.isNull()) {
        QDomElement imagingTime = imageinfo.firstChildElement("imagingTime");
        
        QString starttimestr = imagingTime.firstChildElement("start").text().trimmed();
        QString endtimestr = imagingTime.firstChildElement("end").text().trimmed();

        TimestampMicroseconds starttime = parseAndConvert(starttimestr.toStdString());
        TimestampMicroseconds endtime = parseAndConvert(endtimestr.toStdString());

        start = starttime.msecsSinceEpoch / 1000.0 + starttime.microseconds / 100000.0;
        end = endtime.msecsSinceEpoch / 1000.0 + endtime.microseconds / 100000.0;
        
        // 打印starttime,endtime
		qDebug() << u8"成像开始时间(parse)：" << starttime.msecsSinceEpoch << "\t" << starttime.microseconds;
		qDebug() << u8"成像结束时间(parse)：" << endtime.msecsSinceEpoch << "\t" << endtime.microseconds;

        qDebug() << u8"成像开始时间：" << start <<"\t"<< starttimestr;
        qDebug() << u8"成像结束时间：" << end << "\t" << endtimestr;

     
        nearRange = imageinfo.firstChildElement("nearRange").text().toDouble();
        refRange = imageinfo.firstChildElement("refRange").text().toDouble();
        eqvFs = imageinfo.firstChildElement("eqvFs").text().toDouble();
        eqvPRF = imageinfo.firstChildElement("eqvPRF").text().toDouble();
        QDomElement center = imageinfo.firstChildElement("center");
        latitude_center = center.firstChildElement("latitude").text().toDouble();
        longitude_center = center.firstChildElement("longitude").text().toDouble();
        QDomElement corner = imageinfo.firstChildElement("corner");
        QDomElement topLeft = corner.firstChildElement("topLeft");
        latitude_topLeft = topLeft.firstChildElement("latitude").text().toDouble();
        longitude_topLeft = topLeft.firstChildElement("longitude").text().toDouble();
        QDomElement topRight = corner.firstChildElement("topRight");
        latitude_topRight = topRight.firstChildElement("latitude").text().toDouble();
        longitude_topRight = topRight.firstChildElement("longitude").text().toDouble();
        QDomElement bottomLeft = corner.firstChildElement("bottomLeft");
        latitude_bottomLeft = bottomLeft.firstChildElement("latitude").text().toDouble();
        longitude_bottomLeft = bottomLeft.firstChildElement("longitude").text().toDouble();
		QDomElement bottomRight = corner.firstChildElement("bottomRight");
		latitude_bottomRight = bottomRight.firstChildElement("latitude").text().toDouble();
		longitude_bottomRight = bottomRight.firstChildElement("longitude").text().toDouble();
		width = imageinfo.firstChildElement("width").text().toInt();
		height = imageinfo.firstChildElement("height").text().toInt();
		widthspace = imageinfo.firstChildElement("widthspace").text().toDouble();
		heightspace = imageinfo.firstChildElement("heightspace").text().toDouble();
		sceneShift = imageinfo.firstChildElement("sceneShift").text().toDouble();
		imagebit = imageinfo.firstChildElement("imagebit").text();
		QDomElement qualifyValue = imageinfo.firstChildElement("QualifyValue");

        
         bool HH_QualifyValueISNULL=false;
         bool HV_QualifyValueISNULL=false;
         bool VH_QualifyValueISNULL=false;
         bool VV_QualifyValueISNULL = false;



		HH_QualifyValue = qualifyValue.firstChildElement("HH").text().toDouble(&HH_QualifyValueISNULL);
		HV_QualifyValue = qualifyValue.firstChildElement("HV").text().toDouble(&HV_QualifyValueISNULL);
        VH_QualifyValue = qualifyValue.firstChildElement("HH").text().toDouble(&VH_QualifyValueISNULL);
        VV_QualifyValue = qualifyValue.firstChildElement("HV").text().toDouble(&VV_QualifyValueISNULL);


		HH_QualifyValue = HH_QualifyValueISNULL ? HH_QualifyValue : -1;
		HV_QualifyValue = HV_QualifyValueISNULL ? HV_QualifyValue : -1;
		VH_QualifyValue = VH_QualifyValueISNULL ? VH_QualifyValue : -1;
		VV_QualifyValue = VV_QualifyValueISNULL ? VV_QualifyValue : -1;


		QDomElement echoSaturation = imageinfo.firstChildElement("echoSaturation");
		HH_echoSaturation = echoSaturation.firstChildElement("HH").text().toDouble();
		HV_echoSaturation = echoSaturation.firstChildElement("HV").text().toDouble();
		incidenceAngleNearRange = imageinfo.firstChildElement("incidenceAngleNearRange").text().toDouble();
		incidenceAngleFarRange = imageinfo.firstChildElement("incidenceAngleFarRange").text().toDouble();

        qDebug() << u8"\nImage Info Data:";
        qDebug() << u8"Start:" << start;
        qDebug() << u8"End:" << end;
        qDebug() << u8"Near Range:" << nearRange;
        qDebug() << u8"Ref Range:" << refRange;
        qDebug() << u8"Eqv Fs:" << eqvFs;
        qDebug() << u8"Eqv PRF:" << eqvPRF;
        qDebug() << u8"Center Latitude:" << latitude_center << ", Longitude:" << longitude_center;
        qDebug() << u8"Top Left Corner Latitude:" << latitude_topLeft << ", Longitude:" << longitude_topLeft;
        qDebug() << u8"Top Right Corner Latitude:" << latitude_topRight << ", Longitude:" << longitude_topRight;
        qDebug() << u8"Bottom Left Corner Latitude:" << latitude_bottomLeft << ", Longitude:" << longitude_bottomLeft;
        qDebug() << u8"Bottom Right Corner Latitude:" << latitude_bottomRight << ", Longitude:" << longitude_bottomRight;
        qDebug() << u8"Width:" << width;
        qDebug() << u8"Height:" << height;
        qDebug() << u8"Width Space:" << widthspace;
        qDebug() << u8"Height Space:" << heightspace;
        qDebug() << u8"Scene Shift:" << sceneShift;
        qDebug() << u8"Image Bit:" << imagebit;
        qDebug() << u8"HH Qualify Value:" << HH_QualifyValue;
        qDebug() << u8"HV Qualify Value:" << HV_QualifyValue;
        qDebug() << u8"HH Echo Saturation:" << HH_echoSaturation;
        qDebug() << u8"HV Echo Saturation:" << HV_echoSaturation;
        qDebug() << u8"incidenceAngleNearRange:" << incidenceAngleNearRange;
        qDebug() << u8"incidenceAngleFarRange:" << incidenceAngleFarRange;
    }
}

void SatelliteGF3xmlParser::parseAdditionalData() {
    QDomElement processinfo = xml.firstChildElement("product").firstChildElement("processinfo");
    QDomElement calibrationConst = processinfo.firstChildElement("CalibrationConst");
    if (!calibrationConst.isNull()) {

        bool HH_CalibrationConstISNULL=false;
        bool HV_CalibrationConstISNULL=false;
        bool VH_CalibrationConstISNULL=false;
        bool VV_CalibrationConstISNULL = false;
        HH_CalibrationConst = calibrationConst.firstChildElement("HH").text().toDouble(&HH_CalibrationConstISNULL);
        HV_CalibrationConst = calibrationConst.firstChildElement("HV").text().toDouble(&HV_CalibrationConstISNULL);
        VH_CalibrationConst = calibrationConst.firstChildElement("VH").text().toDouble(&VH_CalibrationConstISNULL);
        VV_CalibrationConst = calibrationConst.firstChildElement("VV").text().toDouble(&VV_CalibrationConstISNULL);

		HH_CalibrationConst = HH_CalibrationConstISNULL ? HH_CalibrationConst : -1;
		HV_CalibrationConst = HV_CalibrationConstISNULL ? HV_CalibrationConst : -1;
		VH_CalibrationConst = VH_CalibrationConstISNULL ? VH_CalibrationConst : -1;
		VV_CalibrationConst = VV_CalibrationConstISNULL ? VV_CalibrationConst : -1;



        qDebug() << u8"\nCalibration Const Data:";
        qDebug() << u8"HH Calibration Const:" << HH_CalibrationConst;
        qDebug() << u8"HV Calibration Const:" << HV_CalibrationConst;
        qDebug() << u8"VH Calibration Const:" << VH_CalibrationConst;
        qDebug() << u8"VV Calibration Const:" << VV_CalibrationConst;
    }

    AzFdc0 = processinfo.firstChildElement("AzFdc0").text().toDouble();
    AzFdc1 = processinfo.firstChildElement("AzFdc1").text().toDouble();
    QDomElement sensorNode = xml.firstChildElement("product").firstChildElement("sensor");
    sensorID = sensorNode.firstChildElement("sensorID").text();
    imagingMode = sensorNode.firstChildElement("imagingMode").text();
    lamda = sensorNode.firstChildElement("lamda").text().toDouble();
    RadarCenterFrequency = sensorNode.firstChildElement("RadarCenterFrequency").text().toDouble();

    TotalProcessedAzimuthBandWidth = processinfo.firstChildElement("TotalProcessedAzimuthBandWidth").text().toDouble();
    DopplerParametersReferenceTime = processinfo.firstChildElement("DopplerParametersReferenceTime").text().toDouble();

    QDomElement dopplerCentroidCoefficients = processinfo.firstChildElement("DopplerCentroidCoefficients");
    d0 = dopplerCentroidCoefficients.firstChildElement("d0").text().toDouble();
    d1 = dopplerCentroidCoefficients.firstChildElement("d1").text().toDouble();
    d2 = dopplerCentroidCoefficients.firstChildElement("d2").text().toDouble();
    d3 = dopplerCentroidCoefficients.firstChildElement("d3").text().toDouble();
    d4 = dopplerCentroidCoefficients.firstChildElement("d4").text().toDouble();

    QDomElement dopplerRateValuesCoefficients = processinfo.firstChildElement("DopplerRateValuesCoefficients");
    r0 = dopplerRateValuesCoefficients.firstChildElement("r0").text().toDouble();
    r1 = dopplerRateValuesCoefficients.firstChildElement("r1").text().toDouble();
    r2 = dopplerRateValuesCoefficients.firstChildElement("r2").text().toDouble();
    r3 = dopplerRateValuesCoefficients.firstChildElement("r3").text().toDouble();
    r4 = dopplerRateValuesCoefficients.firstChildElement("r4").text().toDouble();

    DEM = processinfo.firstChildElement("DEM").text().toDouble();

    qDebug() << u8"\nAdditional Data:";
    qDebug() << u8"AzFdc0:" << AzFdc0;
    qDebug() << u8"AzFdc1:" << AzFdc1;
    qDebug() << u8"Sensor ID:" << sensorID;
    qDebug() << u8"Imaging Mode:" << imagingMode;
    qDebug() << u8"Lambda:" << lamda;
    qDebug() << u8"Radar Center Frequency:" << RadarCenterFrequency;
    qDebug() << u8"Total Processed Azimuth Band Width:" << TotalProcessedAzimuthBandWidth;
    qDebug() << u8"Doppler Parameters Reference Time:" << DopplerParametersReferenceTime;
    qDebug() << u8"Doppler Centroid Coefficients: d0=" << d0 << ", d1=" << d1 << ", d2=" << d2 << ", d3=" << d3 << ", d4=" << d4;
    qDebug() << u8"Doppler Rate Values Coefficients: r0=" << r0 << ", r1=" << r1 << ", r2=" << r2 << ", r3=" << r3 << ", r4=" << r4;
    qDebug() << u8"DEM:" << DEM;
}
