// https://help.qlik.com/en-US/sense-developer/June2020/Subsystems/Mashups/Content/Sense_Mashups/mashups-authentication-cloud.htm
// https://qlik.dev/tutorials/build-a-simple-web-app
const config = {
  host: "gear-presales.eu.qlikcloud.com",
  secure: true,
  port: 443,
  prefix: "",
  webIntegrationId: 'n4kMLH62hvXXC84q2vdfW15WUvrUw-HU',
  appId: "2d03e11f-f3d8-4ba7-a123-be5a282fb9f1"
}
const urlLoggedIn = "/api/v1/audits";//Use GET request to see if you are authenticated
const urlLogin = "/login";

const init = async () => {
  const response = await fetch(`https://${config.host}${urlLoggedIn}`, {
      credentials: 'include',
      headers: {                  
          'Qlik-Web-Integration-ID': config.webIntegrationId
      }
  })
  if(response.status===401){
    const url = new URL(`https://${config.host}/login`);
    url.searchParams.append('returnto', 'http://localhost:3000/mystats');
    url.searchParams.append('qlik-web-integration-id', config.webIntegrationId);
    window.location.href = url;
  }
  const { qdtCapabilityApp, QdtViz } = QdtComponents;
  const capabilityApiAppPromise  = qdtCapabilityApp(config);
  const app = await capabilityApiAppPromise;
  
  QdtViz({
    element: document.getElementById('currentselections'),
    app,
    options: {
      id: 'CurrentSelections',
      height: "40px"
    },
  });

  QdtViz({
    element: document.getElementById('qdt1'),
    app,
    options: {
      type: 'table',
      id: 'mCjaU',
      height: "300px"
    },
  });

  QdtViz({
    element: document.getElementById('qdt1a'),
    app,
    options: {
      type: "piechart",
      id: 'XrnNdj',
      height: "300px"
    },
  });

  

  QdtViz({
    element: document.getElementById('qdt3'),
    app,
    options: {
      type: "linechart",
      id: 'QfYrJj',
      height: "300px"
    },
  });

  QdtViz({
    element: document.getElementById('qdt4'),
    app,
    options: {
      type: "barchart",
      id: 'JvSJCW',
      height: "300px"
    },
  });

  QdtViz({
    element: document.getElementById('totalprovkpi'),
    app,
    options: {
      id: 'zWDmhfq',
      height: "100px"
    },
  });

  QdtViz({
    element: document.getElementById('filterstatus'),
    app,
    options: {
      id: 'uznaVCC',
      height: "40px"
    },
  });
  

  QdtViz({
    element: document.getElementById('costhismonth'),
    app,
    options: {
      type: "kpi",
      id: "GkRz",
      height: "100px"
    },
  });

  QdtViz({
    element: document.getElementById('statusprov'),
    app,
    options: {
      id: 'kXyQPa',
      height: "150px"
    },
  });
}