//==========================================
// Poi3D Portal 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

Poi3D mapping:
Poi3dStorageConnector.categories                                   = Dummy (only one initialized)
Poi3dStorageConnector.categories[].documentCollections             = Poi3dWorkGroup from user
Poi3dStorageConnector.categories[].documentCollections[].documents = Poi3dDocument from work groups
*/

var Poi3dPortalConnector = function ()
{
  this.configuration.context = "Poi3dPortal";

  //Connector specific variables =============================
  this.nrOfWorkgroupsToLoad = 0;
  this.currentUser = null;

  //Connector specific JS libraries  =========================
  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.categories.push(new Poi3dStorageCategory());//only one (invisible) category
    this.currentUser = new Poi3dUser();
    this.currentUser.setCallbackObject(this);
    this.currentUser.setLoginSuccessCallback(this.onUserLoggedIn);
    this.currentUser.setErrorCallback(this.onPoi3dConnectError);

    Poi3dHelpers.setNotificationHandler(this.onPoi3dNotification,this);

    this.readConfigurationFromBrowserStorage();
  };//Poi3dPortalConnector.init (base function overwrite)

  this.login = function (userName,userPwd)
  {
    if(this.currentUser.isLoggedIn() == false)
      this.currentUser.logInAndLoad(userName,userPwd);
  };//Poi3dPortalConnector.login (base function overwrite)

  this.logoff = function ()
  {
    if(this.currentUser.isLoggedIn() == true)
      this.currentUser.logOff();

    this.isUserLoggedIn = false;
  };//Poi3dPortalConnector.logoff (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;
  };//Poi3dPortalConnector.loadPreview (base function overwrite)

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

  //Connector specific methods: ================================
  this.onPoi3dNotification = function(event)
  {
    var poi3dDoc = null;
    var storeDoc = null;
    let did = "";

    if(event.data.calledFrom == undefined) return;
    switch(event.data.info)
    {
      case "loadDocAttributesSuccess":
        //aktuell nur unverschlüsselte Attribute!!!
        poi3dDoc = event.data.calledFrom.getCurrentDoc();
        did = poi3dDoc.getDocId();
        storeDoc = this.categories[0].findStorageDocument(poi3dDoc.getDocId());

        if(storeDoc != null)
        {
          let poi3dAttributes = poi3dDoc.getDocAttributeObject().getTopModelAttributes();
          let storeDocAttribs = storeDoc.getAttributes();
          if((storeDocAttribs.length == 0)&&(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)...
        }//if(storeDoc != null)
        else
        {
          let t1 = poi3dDoc.getTitle();
          let t2 = poi3dDoc.getDocFileName();
        }

        break;
      case "loadFileAttachmentsSuccess":
        poi3dDoc = event.data.calledFrom.getCurrentDoc();
        did = poi3dDoc.getDocId();
        storeDoc = this.categories[0].findStorageDocument(poi3dDoc.getDocId());

        if(storeDoc != null)
        {
          let poi3dAttachments = poi3dDoc.getFileAttachments();
          let storeDocAttachments = storeDoc.getFileAttachments();
          if((storeDocAttachments.length == 0)&&(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();
          }//if((storeDoc.getAttributes().length == 0)...
        }
        else
        {
          let t1 = poi3dDoc.getTitle();
          let t2 = poi3dDoc.getDocFileName();
        }
        break;
    }
  };

  this.onWorkGroupLoaded = function (loadedWorkGroup)
  {
    let groupDocuments = null;
    let groupDocument = null;
    let documentCollection = null;
    let documentArray = null;
    let storageDocument = null;
    let documentCollectionArray = this.categories[0].getDocumentCollections();

    this.nrOfWorkgroupsToLoad --;

    groupDocuments = loadedWorkGroup.getGroupDocuments();
    if(groupDocuments.length > 0)
    {
      documentCollection = new Poi3dStorageDocumentCollection(this.categories[0]);
      documentCollection.setTitle(loadedWorkGroup.getTitle());
      documentCollectionArray.push(documentCollection);

      documentArray = documentCollection.getDocuments();

      for ( let k =0; k< groupDocuments.length; k++)
      {
        groupDocument = groupDocuments[k];

        groupDocument.loadDocument(this.currentUser);

        let storeDoc = this.categories[0].findStorageDocument(groupDocument.getDocId());

        if(storeDoc == null)
        {
          storageDocument = new Poi3dStorageDocument(documentCollection);
          storageDocument.setTitle(groupDocument.getTitle());
          storageDocument.setDescription(groupDocument.getDescription());
          storageDocument.setThumbnailUrl(groupDocument.getPreviewUrl(this.currentUser,"read"));
          storageDocument.setPreviewUrl(groupDocument.getDocUrl(this.currentUser,"read"));
          storageDocument.setFileName(groupDocument.getDocFileName());
          storageDocument.setDocId(groupDocument.getDocId());
          storageDocument.nativeDocument = groupDocument;

          documentArray.push(storageDocument);

          //aktuell nur unverschlüsselte Attribute!!!
          docAttrAttachment = groupDocument.getDocAttributeObject();
          docAttrAttachment.readFromStorage();

          fileAttachment = groupDocument.getFileAttachmentObject();
          fileAttachment.readFromStorage();
        }
        else
          documentArray.push(storeDoc);

        documentCollection.setLoadState(true);
      }//for ( let k =0; k< groupDocuments.length; k++)
    }//if(userDocuments.length > 0)

    if(this.nrOfWorkgroupsToLoad ==0)
    {
      if(this.categoriesLoadedCb != null) this.categoriesLoadedCb();
      if(this.documentCollectionLoadedCb != null) this.documentCollectionLoadedCb();
    }
  };//Poi3dPortalConnector.onWorkGroupLoaded

  this.onUserLoggedIn = function ()
  {
    this.updateStateTexts("Logged in","");
    canBeUsed("loginBut",false);
    canBeUsed("saveBut",true);

    this.isUserLoggedIn = true;

    let documentCollection = null;
    let documentArray = null;
    let storageDocument = null;

    //own documents
    let userDocuments = this.currentUser.getUserDocuments();
    let userDocument = null;
    let docAttrAttachment = null;
    let fileAttachment = null;
    let documentCollectionArray = this.categories[0].getDocumentCollections();

    if(userDocuments.length > 0)
    {
      documentCollection = new Poi3dStorageDocumentCollection(this.categories[0]);
      documentCollection.setTitle("Own Documents");
      documentCollectionArray.push(documentCollection);

      documentArray = documentCollection.getDocuments();

      for (let k =0; k< userDocuments.length; k++)
      {
        userDocument = userDocuments[k];
        userDocument.loadDocument(this.currentUser);

        storageDocument = new Poi3dStorageDocument(documentCollection);
        storageDocument.setTitle(userDocument.getTitle());
        storageDocument.setDescription(userDocument.getDescription());
        storageDocument.setThumbnailUrl(userDocument.getPreviewUrl(this.currentUser,"read"));
        storageDocument.setPreviewUrl(userDocument.getDocUrl(this.currentUser,"read"));
        storageDocument.setFileName(userDocument.getDocFileName());
        storageDocument.setDocId(userDocument.getDocId());
        storageDocument.nativeDocument = userDocument;

        documentArray.push(storageDocument);

        //aktuell nur unverschlüsselte Attribute!!!
        docAttrAttachment = userDocument.getDocAttributeObject();
        docAttrAttachment.readFromStorage();

        fileAttachment = userDocument.getFileAttachmentObject();
        fileAttachment.readFromStorage();
      }
      documentCollection.setLoadState(true);
    }

    //workgroup documents
    let userWorkGroups = this.currentUser.getWorkGroups();
    let userWorkGroup = null;

    this.nrOfWorkgroupsToLoad = 0;
    for ( let i =0; i< userWorkGroups.length; i++)
    {
      if((userWorkGroups[i].getWgState() != "rejected")&&(userWorkGroups[i].getWgState() != "deleted")&&(userWorkGroups[i].getWgState() != "error"))
      {
        this.nrOfWorkgroupsToLoad++;
        userWorkGroup = userWorkGroups[i];
        userWorkGroup.setCallbackObject(this);
        userWorkGroup.setLoadSuccessCallback(this.onWorkGroupLoaded);
        userWorkGroup.setErrorCallback(this.onPoi3dConnectError);
      }//if((userWorkGroups[i].getWgState()
    }//for ( let i =0; i< userWorkGroups.length; i++)

    if((this.nrOfWorkgroupsToLoad ==0) && (this.documentCollectionLoadedCb != null))
      this.documentCollectionLoadedCb();

  };//Poi3dPortalConnector.onUserLoggedIn

  this.onPoi3dConnectError = function (errorMessage)
  {
    this.updateStateTexts(errorMessage,"error");
  };//Poi3dPortalConnector.onPoi3dConnectError

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