//==========================================
// Poi3D Catalog connector ------------------
//==========================================

/*
Data Structure:
Poi3dStorageConnector
  this.categories = Array of Poi3dStorageCategory's
    _documentCollections = Array of Poi3dStorageDocumentCollection's
      _documents = Array of Poi3dStorageDocument's
        _fileAttachments = Array of Poi3dStorageFileAttachment's
        _attributes = Array of Poi3dStorageAttribute's

Catalog mapping:
Poi3dStorageConnector.categories                                   = Poi3dCatalog
Poi3dStorageConnector.categories[].documentCollections             = Poi3dWorkGroup
Poi3dStorageConnector.categories[].documentCollections[].documents = Poi3dDocument
*/

var Poi3dCatalogConnector = function ()
{
  this.configuration.catalogIndex = "https://mypoi3d.com/Poi3dCatalogs";

  //Connector specific variables =============================
  this.configuration.appId = "";
  this.poi3dConnector = null;

  //Connector specific JS libraries  =========================
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dViewAdapter.js",loadFct:null});
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dHelpers.js",loadFct:null});
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dUser.js",loadFct:null});
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dDocument.js",loadFct:null});
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dLanguage.js",loadFct:null});
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dAttachments.js",loadFct:null});
  this.libraries.push({mLoc:"Poi3d/Scripts/Poi3dWorkGroup.js",loadFct:null});

  //Base function overwrites: ================================
  this.init = function ()
  {
    this.poi3dConnector = new Poi3dViewAdapter("catalog");
    this.poi3dConnector.registerCallback("catalogIndexLoaded",this.onCatalogIndexLoaded);
    this.poi3dConnector.registerCallback("externalCatalogLoaded",this.onCatalogLoaded);
    this.poi3dConnector.registerCallback("updateModelFileAttachments",this.onFileAttachmentsLoaded);
    this.poi3dConnector.registerCallback("updateModelDocAttributes",this.onDocAttributesLoaded);
    this.poi3dConnector.initializeAccess();

    this.readConfigurationFromBrowserStorage();

    this.updateStateTexts("Loading Catalog Index","");
    this.poi3dConnector.loadCatalogIndex(this.configuration.catalogIndex);
  };//Poi3dCatalogConnector.init (base function overwrite)

  this.loadPreview = async function (documentObject)
  {
    let loadPromise = new Promise(function(resolve)
    {
      documentObject.setDocData(null);//load by URL
      resolve(0);
    });//loadPromise = new Promise
    return await loadPromise;
  };//Poi3dCatalogConnector.loadPreview (base function overwrite)

  this.loadCategory = function (selectedCategory)
  {
    this.updateStateTexts("Loading " + selectedCategory.poi3dCatalog.getTitle(),"");

    if(selectedCategory.getLoadState() == false)
    {
      this.poi3dConnector.loadExternalCatalog(selectedCategory.poi3dCatalog.getCatalogUrl(),selectedCategory.poi3dCatalog.getTitle());
    }
  };//Poi3dProfilePlmConnector.loadDocumentCollection (base function overwrite)

  this.openDocumentInPortal = function (documentObject)//docUrl statt DB-ID
  {
    if(documentObject != null)
    {
      let docId = documentObject.getDocId();
      let groupId = documentObject.getCollection().getId();
      let ctlgUrl = documentObject.getCollection().getCategory().poi3dCatalog.getCatalogUrl();

      let params = "?docUrl=" + ctlgUrl + "/" + groupId + "/" + docId;
      window.open(this.configuration.poi3dPortalAddress + params,'_blank');
    }
  };//Poi3dProfilePlmConnector.openDocumentInPortal (base function overwrite)

  this.downloadFileAttachment = function (fileAttachmentObject)
  {
    fileAttachmentObject.nativeFileAttachment.downloadFile(this.poi3dConnector.getPoi3dUser());
  };//Poi3dPortalConnector.downloadFileAttachment (base function overwrite)

  //Connector specific methods: ================================

  this.onCatalogIndexLoaded = function()
  {
    let storageCategory = null;
    let documentCollection = null;
    let documentCollectionArray = null;

    this.updateStateTexts("","");

    let loadedCatalogs = this.poi3dConnector.getExternalCatalogs("external");
    for(let i = 0; i < loadedCatalogs.length; i++)
    {
      storageCategory = new Poi3dStorageCategory();
      storageCategory.setTitle(loadedCatalogs[i].getTitle());
      storageCategory.setId("id-" + i);

      //add catalog specific properties
      storageCategory.poi3dCatalog = loadedCatalogs[i];

      this.categories.push(storageCategory);
    }

    if(this.categoryListLoadedCb != null) this.categoryListLoadedCb();

    if((this.categorySelectedCb != null)&&(this.categories.length > 0))
      this.categorySelectedCb(this.categories[0]);

  }.bind(this);//this.onCatalogIndexLoaded

  this.onCatalogLoaded = function(ctlgUrl)
  {
    let doc = null;
    let ctlgChapters = null;
    let chapterDocuments = null;

    let docCollections = null;
    let docCollection = null;
    let docCollectionDocs = null;

    let foundCategory = this.categories.find((ctgry) => ctgry.poi3dCatalog.getCatalogUrl() === ctlgUrl);
    if((foundCategory != null)&&(foundCategory.getLoadState() == false))
    {
      docCollections = foundCategory.getDocumentCollections();
      ctlgChapters = foundCategory.poi3dCatalog.getEntries(); // -> Poi3dWorkGroup

      //load catalog chapters
      for(let i = 0; i < ctlgChapters.length; i++)
      {
        docCollection = new Poi3dStorageDocumentCollection(foundCategory);
        docCollection.setId(ctlgChapters[i].getGroupId());
        docCollection.setTitle(ctlgChapters[i].getTitle());
        docCollections.push(docCollection);
        docCollectionDocs = docCollection.getDocuments();

        //load chapter documents
        chapterDocuments = ctlgChapters[i].getGroupDocuments();
        for ( let k =0; k < chapterDocuments.length; k++)
        {
          doc = new Poi3dStorageDocument(docCollection);
          doc.setDocId(chapterDocuments[k].getDocId());
          doc.setDescription(chapterDocuments[k].getDescription());
          doc.setTitle(chapterDocuments[k].getTitle())

          doc.setFileName(chapterDocuments[k].getDocUrl(this.poi3dConnector.getPoi3dUser(),"read"));
          doc.setPreviewUrl(chapterDocuments[k].getDocUrl(this.poi3dConnector.getPoi3dUser(),"read"));
          doc.setThumbnailUrl(chapterDocuments[k].getPreviewUrl(this.poi3dConnector.getPoi3dUser(),"read"));

          docCollectionDocs.push(doc);

          chapterDocuments[k].getFileAttachmentObject().readFromStorage();
          chapterDocuments[k].getDocAttributeObject().readFromStorage();

        }//for ( let k =0; k < chapterDocuments.length; k++)
      }//for(let i = 0; i < ctlgChapters.length; i++)

      foundCategory.setLoadState(true);

      this.updateStateTexts("Catalog loaded")

      //!!! grafik update
      canBeUsed("loadCategoryBut",false);

      if(this.documentCollectionLoadedCb != null)
        this.documentCollectionLoadedCb(foundCategory);

    }//if((foundCategory == null)
  }.bind(this);//this.onCatalogLoaded

  this.onFileAttachmentsLoaded = function(poi3dAttachments,poi3dDocument)
  {
    let storeDoc = this.findStorageDocument(poi3dDocument.getDocId());
    if(storeDoc != null)
    {
      let poi3dAttachments = poi3dDocument.getFileAttachments();
      let storeDocAttachments = storeDoc.getFileAttachments();

      if(poi3dAttachments.length > 0)
      {
        let poi3dAtt = null;
        let storeAtt = null;

        for(let i=0; i<poi3dAttachments.length; i++)
        {
          poi3dAtt = poi3dAttachments[i];
          storeAtt = new Poi3dStorageFileAttachment();

          storeAtt.setTitle(poi3dAtt.getTitle());
          storeAtt.setDescription(poi3dAtt.getDesc());

          //extension of Poi3dStorageFileAttachment
          storeAtt.nativeFileAttachment = poi3dAtt;

          storeDocAttachments.push(storeAtt);
        }

        if(currentDocument == storeDoc)
          updateDocumentInformation();
      }
    }
  }.bind(this);//this.onCatalogLoaded

  this.onDocAttributesLoaded = function(poi3dAttributes,poi3dDocument)
  {
    let storeDoc = this.findStorageDocument(poi3dDocument.getDocId());
    if(storeDoc != null)
    {
      let poi3dAttributes = poi3dDocument.getDocAttributeObject().getTopModelAttributes();
      let storeDocAttribs = storeDoc.getAttributes();

      if(poi3dAttributes.length > 0)
      {
        let poi3dAtt = null;
        let storeAtt = null;

        for(let i=0; i<poi3dAttributes.length; i++)
        {
          poi3dAtt = poi3dAttributes[i];
          storeAtt = new Poi3dStorageAttribute();
          storeAtt.setKey(poi3dAtt.getKey());
          storeAtt.setValue(poi3dAtt.getValue());
          storeAtt.setTitle(poi3dAtt.getTitle());

          storeDocAttribs.push(storeAtt);
        }

        if(currentDocument == storeDoc)
          updateDocumentInformation();
      }//if((storeDoc.getAttributes().length == 0)...
    }
  }.bind(this);//this.onCatalogLoaded

};//Poi3dCatalogConnector
Poi3dCatalogConnector.prototype = new Poi3dStorageConnector(); //derived from Poi3dStorageConnector
