QMLResourceList MasterCatalogModel::resources(){
    CatalogModel *catalogModel = selectedCatalog();
    if ( catalogModel)
        return catalogModel->resources();

    return QQmlListProperty<ResourceModel>();
}
QQmlListProperty<IlwisObjectModel> MasterCatalogModel::selectedData()
{
     CatalogModel *catalogModel = selectedCatalog();
     if ( catalogModel)
         return catalogModel->selectedData();
     return QQmlListProperty<IlwisObjectModel>();
}
QString MasterCatalogModel::changeCatalog(const QString &inpath){
    if ( inpath == "" || inpath == sUNDEF)
        return "";
    CatalogModel *model = selectedCatalog();
    if  ( model && model->url() == inpath)
        return "";

    QString path = inpath;
    int index = inpath.indexOf("/..");
    if ( index != -1){
        path = path.left(path.size() - 3);
        index = path.lastIndexOf("/");
        if ( index == -1)
            return "";
        path = path.left(index);
    }
    //we are not sure here if it is a filepath or an url; we need an url though
    QFileInfo inf(path);
    // qfileinfo only works with filepaths no urls, so if it exists it is a path
    QString url =  inf.exists() ? QUrl::fromLocalFile(path).toString() : path;

    for(int i =0; i < _splitCatalogs[_activeSplit].size(); ++i){
        CatalogModel *cat = _splitCatalogs[_activeSplit][i];
        if ( cat->url() == url){
            pushToFront(i);
            emit emitResourcesChanged();
            return cat->url();
        }
    }
    return url;
}
void MasterCatalogModel::setObjectFilterCurrentCatalog(const QString &objecttype, bool state)
{
    CatalogModel *catalogModel = selectedCatalog();
    if ( catalogModel){
        catalogModel->filterChanged(objecttype, state);
        emit resourcesChanged();
    }
}
void MasterCatalogModel::setCatalogMetadata(const QString& displayName, const QString& description){
    if ( std::find(_bookmarkedList.begin(), _bookmarkedList.end(), _currentUrl) != _bookmarkedList.end()){
        if ( _activeCatalogs.find(_currentUrl) != _activeCatalogs.end()){
        CatalogModel *model = _activeCatalogs[_currentUrl];
            model->setDisplayName(displayName);
            model->resourceRef().setDescription(description);
        }
    }
}
void MasterCatalogModel::setCatalogMetadata(const QString& displayName, const QString& description){
    CatalogModel *model = selectedCatalog();
    if ( model && _currentbookmarkid != ""){
        model->setDisplayName(displayName);
        model->resourceRef().setDescription(description); 
        QString key = "users/user-0/data-catalog-" + _currentbookmarkid;
        context()->configurationRef().putValue(key + "/label", displayName);
        context()->configurationRef().putValue(key + "/description", description);
    }
}
CatalogModel *MasterCatalogModel::newCatalog(const QString &inpath, const QString& filter)
{
    if ( inpath == "" || inpath == sUNDEF )
        return 0;

    QUrl location(inpath);
    _currentUrl = inpath;
    if ( inpath.indexOf("ilwis://internalcatalog/workspaces") == 0){
        for(auto workspace : _workspaces){
            if ( workspace->url() == inpath){
                emit currentCatalogChanged();
                WorkSpaceModel *wsm = 0; // new WorkSpaceModel(*workspace);
                return wsm;
            }
        }
    }else {
        bool canBeAnimated = false;
        Resource res = mastercatalog()->name2Resource(inpath,itCATALOG);
        if ( res.isValid()){
            canBeAnimated = hasType(res.extendedType(), itCATALOG)        ;
        }else
            res = Resource(inpath, itCATALOG);

        if ( filter != "container=ilwis://mastercatalog")
            res.addProperty("filter",filter);
        res.addProperty("canbeanimated",canBeAnimated);

        CatalogModel *model = 0;
        if ( inpath.indexOf("ilwis://operations") == 0){
            res.addProperty("filter", "(type=" + QString::number(itSINGLEOPERATION) + " or type=" + QString::number(itWORKFLOW) + ")");
            model = new OperationCatalogModel(res, this);
        }else
            model = new CatalogModel(res, CatalogModel::getCatalogType(res, CatalogModel::ctMUTABLE));
        if ( _currentCatalog == 0){
            QString num = context()->configurationRef()("users/" + Ilwis::context()->currentUser() + "/filter-count",QString("0"));
            int n = num.toInt();
            for(int i = 0; i < n; ++i){
                QString basekey = "users/" + Ilwis::context()->currentUser() + "/filters-" + QString::number(i);
                QString name = context()->configurationRef()(basekey + "/filter-name", QString(""));
                QString newfilter = context()->configurationRef()(basekey + "/filter-definition", QString(""));
                model->filter(name,newfilter);
            }
        }
        _currentCatalog = model;
        ICatalog catalog(model->url());
        context()->setWorkingCatalog(catalog);
        model->scanContainer(true, false);
        emit currentCatalogChanged();
        return model;


    }
    return 0;
}
void MasterCatalogModel::refreshWorkingCatalog()
{
    CatalogModel *catalogModel = selectedCatalog();
    if ( catalogModel) {
        auto items = context()->workingCatalog()->items();
        mastercatalog()->removeItems(items);
        context()->workingCatalog()->scan();
        catalogModel->refresh(true);
    }

    emit resourcesChanged();
}
void MasterCatalogModel::setCatalogMetadata(const QString& displayName, const QString& description){
    if ( _selectedBookmarkIndex < 3)
        return;

    CatalogModel *model = _bookmarks[_selectedBookmarkIndex];
    if ( model ){
        model->setDisplayName(displayName);
        model->resourceRef().setDescription(description);
        QString key = "users/user-0/data-catalog-" + _bookmarkids[_selectedBookmarkIndex - 3];
        context()->configurationRef().putValue(key + "/label", displayName);
        context()->configurationRef().putValue(key + "/description", description);
        emit bookmarksChanged();
    }
}
void MasterCatalogModel::scanBookmarks()
{
    QString ids = ilwisconfig("users/" + Ilwis::context()->currentUser() + "/available-catalog-ids",QString(sUNDEF));
    if ( ids != sUNDEF)
        _bookmarkids = ids.split("|");
    QUrl urlWorkingCatalog = context()->workingCatalog()->resource().url();
    _currentUrl = urlWorkingCatalog.toString();
    int count = 3;
    std::vector<Resource> catalogResources;
	bool workingCatIsBookmark = false;
    for(auto id : _bookmarkids){
        QString query = QString("users/" + Ilwis::context()->currentUser() + "/data-catalog-%1").arg(id);
        QString label = ilwisconfig(query + "/label", QString(""));
        QUrl location(ilwisconfig(query + "/url-0", QString("")));
        if ( location.isValid()) {
            QString descr = ilwisconfig(query + "/description", QString(""));
            Resource res(location, itCATALOGVIEW ) ;
            if ( label != "")
                res.name(label,false);
            res.addProperty("filter","container='" + location.toString() +"'");
            res.setDescription(descr);

            if ( OSHelper::neutralizeFileName(urlWorkingCatalog.toString()) == OSHelper::neutralizeFileName(location.toString())){
                CatalogModel *model = 0;
                if ( location.toString().indexOf("ilwis://operations") == 0){
                    model = new OperationCatalogModel(this);
                }else
                    model = new CatalogModel(res, CatalogModel::getCatalogType(res, CatalogModel::ctBOOKMARK));
                model->scanContainer(false, false);
				workingCatIsBookmark = true;
                _bookmarks.push_back(model);

            }else{
                catalogResources.push_back(res);
            }
            ++count;
        }
    }
    count = 0;
    for(auto bookmark : _bookmarks){
        if ( bookmark->resource().url() == urlWorkingCatalog){
            _selectedBookmarkIndex = count;
        }
        ++count;
    }

    _workspaces.push_back(new WorkSpaceModel("default", this));
    QString availableWorkspaces = Ilwis::ilwisconfig("users/" + Ilwis::context()->currentUser() + "/workspaces",QString(""));
    if ( availableWorkspaces != ""){
        loadWorkSpaces(availableWorkspaces);
    }
    uicontext()->setCurrentWorkSpace(_workspaces.back());

    // workspaces[0] is the default workspace; its view can't be correct(yet) as it is created before any views
    // are determined. as the default has a starting view that must point to the start working catalog it will
    // search for the workspace that represents this and copy its view
    setDefaultView();

	if(!workingCatIsBookmark)
		catalogResources.push_back(context()->workingCatalog()->resource());
    QList<CatalogModel *> models = startBackgroundScans(catalogResources);

    for(auto iter = models.begin(); iter != models.end(); ++iter){
        _bookmarks.push_back(*iter);
    }

    if ( _currentUrl == ""){
        if ( _bookmarks.size() > 3){
            _selectedBookmarkIndex = 3;
            _currentUrl = _bookmarks[_selectedBookmarkIndex]->url();
        }else {
            QString loc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
            _currentUrl = OSHelper::createFileUrlFromParts(loc, "");
        }
    }
}