bool CoordinateSystemConnector::loadMetaData(IlwisObject* data)
{
    Ilwis3Connector::loadMetaData(data);
    CoordinateSystem *csy = static_cast<CoordinateSystem *>(data);
    QString ellipsoideName;

    IEllipsoid ell = getEllipsoid();
    GeodeticDatum *datum = getDatum(ellipsoideName);
    if ( !ell.isValid() && ellipsoideName != sUNDEF){
        QString ellres = QString("ilwis://tables/ellipsoid?code=%1").arg(ellipsoideName);
       if (!ell.prepare(ellres)) {
              return ERROR1("No ellipsoid for this code %1",ellipsoideName);
       }
    }


    if ( type() == itCONVENTIONALCOORDSYSTEM ) {
        ConventionalCoordinateSystem *csycc = static_cast<ConventionalCoordinateSystem *>(csy);
        IProjection proj = getProjection();
        if ( !proj.isValid()) {
            return ERROR1(ERR_NO_INITIALIZED_1, "projection");
        }
        csycc->setDatum(datum);
        csycc->setEllipsoid(ell);
        csycc->setProjection(proj);
        proj->setCoordinateSystem(csycc);


        proj->setParameter(Projection::pvELLCODE, ell->toProj4());
        csycc->prepare();
    } else if ( type() == itUNKNOWN){
        //TODO other types of csy
    }
    return true;
}
bool CoordinateSystemConnector::loadMetaData(IlwisObject* data, const IOOptions& options)
{
    Ilwis3Connector::loadMetaData(data, options);
    CoordinateSystem *csy = static_cast<CoordinateSystem *>(data);
    QString ellipsoideName;

    IEllipsoid ell = getEllipsoid();
    GeodeticDatum *datum = getDatum(ellipsoideName);
    if ( !ell.isValid() && ellipsoideName != sUNDEF){
        QString ellres = QString("ilwis://tables/ellipsoid?code=%1").arg(ellipsoideName);
       if (!ell.prepare(ellres)) {
              return ERROR1("No ellipsoid for this code %1",ellipsoideName);
       }
    }

    QString cb = _odf->value("CoordSystem", "CoordBounds");
    QStringList cbparts = cb.split(" ");
    if ( cbparts.size() == 4 && cbparts[0] != "-1e+308") {
        bool ok1, ok2, ok3, ok4;
        Envelope box( Coordinate(
                                cbparts[0].toDouble(&ok1),
                                cbparts[1].toDouble(&ok2)),
                           Coordinate(
                                cbparts[2].toDouble(&ok3),
                                cbparts[3].toDouble(&ok4)));
        if ( !( ok1 && ok2 && ok3 && ok4)) {
            return ERROR2(ERR_NO_INITIALIZED_2, TR("envelop"), csy->name());
        }
        csy->envelope(box);
    } else {
        QString type = _odf->value("CoordSystem", "Type");
        if ( type == "LatLon") {
            Envelope box(Coordinate(-180,-90), Coordinate(180,90));
            csy->envelope(box);
        }
    }

    if ( type() == itCONVENTIONALCOORDSYSTEM ) {
        ConventionalCoordinateSystem *csycc = static_cast<ConventionalCoordinateSystem *>(csy);
        IProjection proj = getProjection(csycc);
        if ( !proj.isValid()) {
            return ERROR1(ERR_NO_INITIALIZED_1, "projection");
        }
        csycc->setDatum(datum);
        csycc->setEllipsoid(ell);
        csycc->setProjection(proj);
        proj->setCoordinateSystem(csycc);


        proj->setParameter(Projection::pvELLCODE, ell->toProj4());
        csycc->prepare();
    } else if ( type() == itUNKNOWN){
        //TODO: other types of csy
    }
    return true;
}
void ProjectionImplementationInternal::setCoordinateSystem(ConventionalCoordinateSystem *csy)
{
    ProjectionImplementation::setCoordinateSystem(csy);
    IProjection prj = _coordinateSystem->projection();
    if ( prj.isValid()) {
        _easting = prj->parameter(Projection::pvFALSEEASTING).toDouble();
        _northing = prj->parameter(Projection::pvFALSENORTHING).toDouble();
        _maxis = _coordinateSystem->ellipsoid()->majorAxis();
        _centralMeridian = prj->parameter(Projection::pvCENTRALMERIDIAN).toDouble();
    }


}
bool CoordinateSystemConnector::storeMetaData(IlwisObject *data) {
    bool ok = true;
    if ((ok = Ilwis3Connector::storeMetaData(data, itCOORDSYSTEM)) == false){
        return false;
    }
    ICoordinateSystem csy(static_cast<CoordinateSystem *>(data));
    if (!csy.isValid() || !csy->isValid()){
        return ERROR1(ERR_NO_INITIALIZED_1, "CoordinateSystem");
    }
    Envelope bounds = csy->envelope();
    if(!bounds.isValid()){
        ERROR2(ERR_NO_INITIALIZED_2, "Bounds", csy->name());
        return sUNDEF;
    }

    _odf->setKeyValue("CoordSystem","CoordBounds",QString("%1 %2 %3 %4").
                      arg(bounds.min_corner().x,10,'f').
                      arg(bounds.min_corner().y,10,'f').
                      arg(bounds.max_corner().x,10,'f').
                      arg(bounds.max_corner().y,10,'f'));

    if ( csy->isLatLon()) {
        _odf->setKeyValue("CoordSystem", "Datum", "WGS 1984");
        _odf->setKeyValue("CoordSystem","Type","LatLon");
        if ( csy.as<ConventionalCoordinateSystem>()->ellipsoid().isValid()){
            IEllipsoid ell = csy.as<ConventionalCoordinateSystem>()->ellipsoid();
            _odf->setKeyValue("CoordSystem","Ellipsoid","User Defined");
            _odf->setKeyValue("Ellipsoid","1/f", 1.0 / ell->flattening());
            _odf->setKeyValue("Ellipsoid","a", ell->majorAxis());
        }
    }else{
        IConventionalCoordinateSystem projectedCsy = csy.as<ConventionalCoordinateSystem>();
        if( !projectedCsy->ellipsoid().isValid() || !projectedCsy->projection().isValid()){
                ERROR2(ERR_NO_INITIALIZED_2, "Ellipsoid/Projection", csy->name());
                return sUNDEF;
        }
        QString projectionName = Ilwis3Connector::code2name(projectedCsy->projection()->name(), "projection");
        _odf->setKeyValue("CoordSystem","Type","Projection");
        _odf->setKeyValue("CoordSystem","Projection",projectionName);
        QString ellipsoidName = projectedCsy->ellipsoid()->name();
        //ellipsoidName = Ilwis3Connector::name2Code(ellipsoidName, "ellipsoid");
        if ( ellipsoidName == sUNDEF){
            ellipsoidName = "User Defined";
            _odf->setKeyValue("Ellipsoid","a",projectedCsy->ellipsoid()->majorAxis() );
            _odf->setKeyValue("Ellipsoid","1/f",projectedCsy->ellipsoid()->flattening() );

        }else
            ellipsoidName = Ilwis3Connector::code2name(ellipsoidName, "ellipsoid");
        _odf->setKeyValue("CoordSystem","Ellipsoid",ellipsoidName);
        IProjection projection = projectedCsy->projection();
        if ( projection->isSet(Projection::pvAZIMCLINE))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvAZIMCLINE),projection->parameter(Projection::pvAZIMCLINE).toDouble());
        if ( projection->isSet(Projection::pvAZIMYAXIS))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvAZIMYAXIS),projection->parameter(Projection::pvAZIMYAXIS).toDouble());
        if ( projection->isSet(Projection::pvHEIGHT))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvHEIGHT),projection->parameter(Projection::pvHEIGHT).toDouble());
        if ( projection->isSet(Projection::pvK0))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvK0),projection->parameter(Projection::pvK0).toDouble());
        if ( projection->isSet(Projection::pvLAT0))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvLAT0),projection->parameter(Projection::pvLAT0).toDouble());
        if ( projection->isSet(Projection::pvLAT1))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvLAT1),projection->parameter(Projection::pvLAT1).toDouble());
        if ( projection->isSet(Projection::pvLAT2))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvLAT2),projection->parameter(Projection::pvLAT2).toDouble());
        if ( projection->isSet(Projection::pvLATTS))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvLATTS),projection->parameter(Projection::pvLATTS).toDouble());
        if ( projection->isSet(Projection::pvLON0))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvLON0),projection->parameter(Projection::pvLON0).toDouble());
        if ( projection->isSet(Projection::pvNORIENTED))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvNORIENTED),projection->parameter(Projection::pvNORIENTED).toString());
        if ( projection->isSet(Projection::pvNORTH))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvNORTH),projection->parameter(Projection::pvNORTH).toString());
        if ( projection->isSet(Projection::pvX0))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvX0),projection->parameter(Projection::pvX0).toDouble());
        if ( projection->isSet(Projection::pvY0))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvY0),projection->parameter(Projection::pvY0).toDouble());
        if ( projection->isSet(Projection::pvZONE))
            _odf->setKeyValue("Projection",prjParam2IlwisName(Projection::pvZONE),projection->parameter(Projection::pvZONE).toInt());

    }
    _odf->store("csy", source().toLocalFile());
    return true;


}
IProjection CoordinateSystemConnector::getProjection(ConventionalCoordinateSystem *csycc) {
    QString projection = _odf->value("CoordSystem","Projection");
    if (projection == "?") {
        QString type = _odf->value("CoordSystem","Type");
        if ( type == "LatLon") {
            projection = type;
            GeodeticDatum *gdata = new GeodeticDatum();
            gdata->fromCode("DWGS84");
            csycc->setDatum(gdata);
        } else
            return IProjection();
    }

    QString code = name2Code(projection, "projection");
    Resource resource(QUrl(QString("ilwis://tables/projection?code=%1").arg(code)), itPROJECTION);

    if ( code == sUNDEF) {
        kernel()->issues()->log(TR("Couldnt find projection %1").arg(projection));
        return IProjection();
    }

    IProjection proj;
    if(!proj.prepare(resource))
        return IProjection();

    bool ok;
    double falseEasting = _odf->value("Projection","False Easting").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvX0, falseEasting);
    double falseNorthing = _odf->value("Projection","False Northing").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvY0, falseNorthing);
    double centralMeridian = _odf->value("Projection","Central Meridian").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvLON0, centralMeridian);
    double centralParllel = _odf->value("Projection","Central Parallel").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvLAT0, centralParllel);
    double standardParllel = _odf->value("Projection","Standard Parallel 1").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvLAT1, standardParllel);
    standardParllel = _odf->value("Projection","Standard Parallel 2").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvLAT2, standardParllel);
    double lattitudeOfTrueScale = _odf->value("Projection","Latitude of True Scale").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvLATTS, lattitudeOfTrueScale);
    double scaleFactor = _odf->value("Projection","Scale Factor").toDouble(&ok);
    if ( ok)
        proj->setParameter(Projection::pvK0, scaleFactor);
    int gzone = _odf->value("Projection","Zone").toInt(&ok);
    if ( ok)
        proj->setParameter(Projection::pvZONE, gzone);
    QString hemisphere = _odf->value("Projection","Northern Hemisphere");
    if ( hemisphere != sUNDEF && code == "utm")
        proj->setParameter(Projection::pvNORTH, hemisphere);

    return proj;
}
QString IlwisObjectModel::getProperty(const QString &propertyname)
{
    try{
        QString property = ResourceModel::getProperty(propertyname);
        if ( property != sUNDEF)
            return property;
        if ( !_ilwisobject.isValid())
            return "";
        if ( propertyname == "latlonenvelope" || propertyname == "envelope"){
            if (hasType(_ilwisobject->ilwisType(), itCOVERAGE)){
                return _ilwisobject.as<Coverage>()->envelope(propertyname == "latlonenvelope").toString();
            } if ( hasType(_ilwisobject->ilwisType(), itCOORDSYSTEM)){
                return _ilwisobject.as<CoordinateSystem>()->envelope(propertyname == "latlonenvelope").toString();
            }
        }
        if ( propertyname == "pixelsize"){
            return pixSizeString();
        }
        if ( propertyname == "centerpixelboundingbox"){
            return centerPixelLocation();
        }
        if ( propertyname == "parentdomain"){
            return parentDomain();
        }
        if ( propertyname == "valuetype"){
            return valueType();
        }
        if ( propertyname == "recordcount"){
            if ( hasType(_ilwisobject->ilwisType(), itTABLE)){
                return QString::number(_ilwisobject.as<Table>()->recordCount());
            }
        }
        if ( propertyname == "columncount"){
            if ( hasType(_ilwisobject->ilwisType(), itTABLE)){
                return QString::number(_ilwisobject.as<Table>()->columnCount());
            }
        }
        if ( propertyname == "polygoncount"){
             if ( hasType(_ilwisobject->ilwisType(), itFEATURE)){
                IFeatureCoverage features = _ilwisobject.as<FeatureCoverage>();
                return QString::number(features->featureCount(itPOLYGON));
             }
        }
        if ( propertyname == "linecount"){
             if ( hasType(_ilwisobject->ilwisType(), itFEATURE)){
                IFeatureCoverage features = _ilwisobject.as<FeatureCoverage>();
                return QString::number(features->featureCount(itLINE));
             }
        }
        if ( propertyname == "pointcount"){
             if ( hasType(_ilwisobject->ilwisType(), itFEATURE)){
                IFeatureCoverage features = _ilwisobject.as<FeatureCoverage>();
                return QString::number(features->featureCount(itPOINT));
             }
        }
        if ( propertyname == "featurecount"){
             if ( hasType(_ilwisobject->ilwisType(), itFEATURE)){
                IFeatureCoverage features = _ilwisobject.as<FeatureCoverage>();
                return QString::number(features->featureCount());
             }
        }
        if ( propertyname == "majoraxis"){
             if ( hasType(_ilwisobject->ilwisType(), itELLIPSOID)){
                IEllipsoid ellipsoid = _ilwisobject.as<Ellipsoid>();
                return QString::number(ellipsoid->majorAxis());
             }
        }
        if ( propertyname == "minoraxis"){
             if ( hasType(_ilwisobject->ilwisType(), itELLIPSOID)){
                IEllipsoid ellipsoid = _ilwisobject.as<Ellipsoid>();
                return QString::number(ellipsoid->minorAxis());
             }
        }
        if ( propertyname == "flattening"){
             if ( hasType(_ilwisobject->ilwisType(), itELLIPSOID)){
                IEllipsoid ellipsoid = _ilwisobject.as<Ellipsoid>();
                return QString::number(ellipsoid->flattening());
             }
        }
        if ( propertyname == "excentricity"){
             if ( hasType(_ilwisobject->ilwisType(), itELLIPSOID)){
                IEllipsoid ellipsoid = _ilwisobject.as<Ellipsoid>();
                return QString::number(ellipsoid->excentricity());
             }
        }
        if (propertyname == "proj4def"){
            IlwisTypes objectype = _ilwisobject->ilwisType();
            if ( hasType( objectype, itPROJECTION | itCONVENTIONALCOORDSYSTEM)){
                IProjection proj;
                if ( hasType(objectype, itCONVENTIONALCOORDSYSTEM)){
                    IConventionalCoordinateSystem csyProj = _ilwisobject.as<ConventionalCoordinateSystem>();
                    if ( csyProj.isValid()){
                        proj = csyProj->projection();
                    }
                }else
                    proj = _ilwisobject.as<Projection>();
                if ( proj.isValid()){
                    return proj->toProj4();
                }
            }

        }

        return "";
    } catch(const ErrorObject& ){
        // no exceptions may escape here
    }
    return "";
}
QQmlListProperty<ProjectionParameterModel> IlwisObjectModel::projectionItems()
{
    IlwisTypes objectype = _ilwisobject->ilwisType();
    if ( hasType( objectype, itPROJECTION | itCONVENTIONALCOORDSYSTEM)){
        IProjection proj;
        _projectionParmItems.clear();
        if ( hasType(objectype, itCONVENTIONALCOORDSYSTEM)){
            IConventionalCoordinateSystem csyProj = _ilwisobject.as<ConventionalCoordinateSystem>();
            if ( csyProj.isValid()){
                proj = csyProj->projection();
            }
        }else
            proj = _ilwisobject.as<Projection>();

        if ( proj.isValid()){
            if ( proj->isUsed(Projection::pvX0))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvX0, this));
            if ( proj->isUsed(Projection::pvY0))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvY0, this));
            if ( proj->isUsed(Projection::pvLON0))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvLON0, this));
            if ( proj->isUsed(Projection::pvLAT0))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvLAT0, this));
            if ( proj->isUsed(Projection::pvLAT1))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvLAT1, this));
            if ( proj->isUsed(Projection::pvLAT2))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvLAT2, this));
            if ( proj->isUsed(Projection::pvLATTS))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvLATTS, this));
            if ( proj->isUsed(Projection::pvK0))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvK0, this));
            if ( proj->isUsed(Projection::pvZONE))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvZONE, this));
            if ( proj->isUsed(Projection::pvHEIGHT))
                _projectionParmItems.append(new ProjectionParameterModel(proj, Projection::pvHEIGHT, this));
        }
        return QQmlListProperty<ProjectionParameterModel>(this, _projectionParmItems);
    }

    return QQmlListProperty<ProjectionParameterModel>();
}
void ConventionalCoordinateSystem::setProjection(const IProjection &proj)
{
    _projection = proj;
    if ( proj->code().contains("longlat") || proj->code().contains("latlon"))
        _unit = "degrees";
}