
importScripts('/synclib.js');

var request = new RequestData(false);
var requestWHash = new RequestData(true);
var SWInterval = {};


function postCustomReqUpdate(url, cachecontent = '', datavalue = '', object = '') {
  self.postMessage({
    type: 'reqcacheupdate', data: {
      url: url,
      datavalue: datavalue,
      object: object,
      content: cachecontent
    }
  });
}


function LoadANDSendReqCache(url, datavalue = '', object = '') {
  let cachecontent = reqcacheload(url, datavalue, object);
  if (!cachedetails) { return false; }
  postCustomReqUpdate(url, cachecontent, datavalue, object);
}

function postcacheHASHupdate(hashkey, content) {
  if (!hashkey) { return false; }
  self.postMessage({
    type: 'cachehashupdate', data: {
      hash: hashkey,
      data: content
    }
  });
}


function FetchAndUpdateDatatoMainThread(urlstring, reqmethod = 'GET', objectdata = '', datavalue = '') {
  let requestWHash = new RequestData(true);
  requestWHash
    .url(urlstring)
    .type(reqmethod)
    .data(objectdata)
    .fromVarCache(false)
    .success((response, responsehash) => {
      if (responsehash) { postcacheHASHupdate(responsehash, response); }
      postCustomReqUpdate(urlstring, response, datavalue, objectdata);
    })
    .error((err) => {
      console.error(err);
    })
    .go();
}

function FetchCachePostInterval(url, interval, method, objectdata, datavalue) {
  if (SWInterval[url]) {
    console.log('Interval for ', url, 'is already set aborting');
    return false;
  }
  SWInterval[url] = setInterval(() => {
    FetchAndUpdateDatatoMainThread(url, method, objectdata, datavalue);
  }, interval);
}

async function saveBlobToOPFS(Filename, blobcontent) {

  if (!Filename || !blobcontent) {
    console.error("Filename and blob content are required.");
    return false;
  }
  try {
    const opfsRoot = await navigator.storage.getDirectory();
    const fileHandle = await opfsRoot.getFileHandle(Filename, { create: true });
    const writableStream = await fileHandle.createWritable();
    await writableStream.write(blobcontent);
    await writableStream.close();
    console.log('Blob saved to OPFS successfully!');
    return true;
  } catch (error) {
    console.error('Error saving blob to OPFS:', error);
    return false;
  }
}

var FileRequestUrl = '/RequestData/File/';

function fetchfileBlob(Hashkey, success, error = false, reqmethod = 'GET') {


  if (!Hashkey) { return false; }
  let requestWHash = new RequestData(true);
  requestWHash
    .url(FileRequestUrl + Hashkey)
    .type(reqmethod)
    .data(null)
    .fromVarCache(false)
    .success(async (response) => {
      if (!response) { return false; }
      if (success) {
        success(response, Hashkey);
      }


        sendBlobfromOPFS(Hashkey,response);
  

      saveBlobToOPFS(Hashkey, response);
    })
    .error((err) => {
      //   console.error(err);
      if (error) {
        error(err);
      }
    })
    .go();

}

async function fetchDataFromOPFS(filename) {
  try {
      const opfsRoot = await navigator.storage.getDirectory();

      // Access the file handle
      const fileHandle = await opfsRoot.getFileHandle(filename, { create: false });

      const file = await fileHandle.getFile();
      const blob = await file.arrayBuffer();
      const contentsBlob = new Blob([blob]);
      return contentsBlob;
  } catch (error) {
      console.error('Error fetching data from OPFS:', error);
      return null; // Return null in case of error
  }
}



function sendBlobfromOPFS(hashkey,blobdata){
  if (!hashkey || !blobdata){return false;}
  self.postMessage({
    type: 'BlobfromOPFS', data: {
      hash: hashkey,
      blob: blobdata
    }
  });
}




function InitializeAutoSyncFunctions() {
  FetchDataAndPostInterval('/get/isloggedin', 'loggedin', 30000);
  FetchDataAndPostInterval('/get/isExec', 'exec', 30000);
  FetchCachePostInterval('/account_settings/details', 60000);
  //FetchCachePostInterval('/ListLeads/List/data', 60000, 'POST');
  //FetchCachePostInterval('/NewLeads/Form/PreferredSitesOption', 60000, 'POST');

}

InitializeAutoSyncFunctions();


self.onmessage = async function (event) {


  const eventdata = event.data;
  const eventtype = event.data.type;
  if (eventtype === 'FileblobOPFS') {
    fetchfileBlob(event.data.hash, event.data.success, event.error);
    return false;
  }

  if (eventtype === 'GetBlobOPFSfromHash') {
    const filename = eventdata.hash; 
    const blob = await fetchDataFromOPFS(filename); 

    if (blob) {
    
        sendBlobfromOPFS(eventdata.hash, blob);
    } else {
        console.error('Failed to fetch blob for:', filename);
        self.postMessage({ type: 'error', message: 'Failed to fetch blob' });
    }
}

};


