(function (RawUserData, $, undefined) {
    // registerBtnHandlers();
    document.getElementById("did-form").addEventListener("submit", function (e) {
        e.preventDefault();
        document.getElementById("p-p").hidden = false
        document.getElementById("p-a").hidden = false
        document.getElementById("p-50").hidden = false
        document.getElementById("p-m").hidden = false
        document.getElementById("p-pg").hidden = false
        document.getElementById("last-50events-table").hidden = false
        document.getElementById("app-inbox-table").hidden = false
        let did = e.target[0].value;
        let cDatas = []
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getRawUserData',
            data: {
                api_key: semusiCommon.getActiveUser.api_key,
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                    did: did,
                })
            },
            dataType: "json",
            success: function (data) {
              if (data.pushToken) {
                  let pt = document.getElementById("push-token");
                  if (data.pushToken.endpoint) {
                    let endpoint = data.pushToken.endpoint;
                    pt.innerHTML = "<h4>Push Token:</h4><small>" + endpoint.substring(endpoint.lastIndexOf("/") + 1) + "</small>";
                  } else {
                    pt.innerHTML = "<h4>Push Token:</h4><small>" + data.pushToken + "</small>";
                  }
                } else {
                  console.error("pushToken is undefined or null");
                }
                
                // app inbox
                $("#app-inbox-table").DataTable({
                    "bDestroy": true,
                    "data": data.appInbox.data,// <-- Data source
                    "aoColumnDefs": [{
                        "aTargets": [0],
                        "mRender": function (data, type, row) {
                            cDatas.push(data)
                            return `<button data-cdataidx="${cDatas.length - 1}" class="view-cdata-btn" data-toggle="modal" data-target="#cdata-modal">view CData</button>`
                        }
                    }],
                    "columns": [
                        { "data": "cdata" },
                        { "data": "ct" },
                        { "data": "et" },
                        { "data": "ln" },
                        { "data": "ni" },
                        { "data": "nid" },
                        { "data": "nm" },
                        { "data": "nt" },
                        { "data": "st" },
                    ],
                    "drawCallback": function () {
                        let btns = document.getElementsByClassName('view-cdata-btn');
                        for (let btn of btns) {
                            btn.addEventListener('click', onViewCdata);
                        }
                    }
                })
  
                // cData  table
                function onViewCdata(e) {
                    let cdataIdx = e.target.getAttribute('data-cdataidx');
                    let cdata = cDatas[Number(cdataIdx)]
                    data = []
                    for (let key in cdata) {
                        data.push({ key: key, value: cdata[key] })
                    }
                    $('#cdata-table').DataTable({
                        bDestroy: true,
                        data: data,
                        columns: [
                            { 'data': 'key' },
                            { 'data': 'value' }
                        ]
                    })
                }
                // last50 events
                $("#last-50events-table").DataTable({
                    "bDestroy": true,
                    "data": data.last50Events,// <-- Data source
                    "columns": [
                        { "data": "eventtime" },
                        { "data": "key" },
                    ]
                })
  
                ////mongo fields
                let mongoFieldsUl = document.getElementById("mongo-fields");
                let mongoFields = flatten(data.mongoFields);
  
                for (key in mongoFields) {
                    let li = document.createElement("li");
                    li.innerHTML = `<strong>${key}</strong>: ${mongoFields[key]}`
                    mongoFieldsUl.append(li)
                }
  
                //psql fields
                let psqlFieldsUl = document.getElementById("pgsql-fields");
                let psqlFields = flatten(data.pgsqlFields);
  
                for (key in psqlFields) {
                    let li = document.createElement("li");
                    li.innerHTML = `<strong>${key}</strong>: ${psqlFields[key]}`
                    psqlFieldsUl.append(li)
                }
  
            }
        });
    })
  
  
    document.getElementById("combined-btn").addEventListener("click", function (e) {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getCombinedLogFile',
            data: {
                api_key: semusiCommon.getActiveUser.api_key,
                args: JSON.stringify({
                    app_id: semusiCommon.ACTIVE_APP_ID,
                })
            },
            success: function (data) {
                let blob = new Blob([data], { type: "application/octetstream" });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = 'combined.log';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                a.remove()
            }
        })
    })
  
    function flattenHelper(ret, obj, parent) {
        for (key in obj) {
            let flatKey = parent ? `${parent}.${key}` : key
            if (typeof obj[key] === "object") {
                flattenHelper(ret, obj[key], flatKey);
            } else {
                ret[flatKey] = obj[key]
            }
        }
    }
  
    function flatten(obj) {
        if (typeof obj !== "object") return;
        let ret = {}
        flattenHelper(ret, obj)
        return ret
    }
    document.getElementById("push-form").addEventListener("submit", function (e) {
          document.getElementById("push-result").innerHTML = "Fatching Data ";
          e.preventDefault();
          let app_id = e.target[0].value;
          let did = e.target[1].value;
          $.ajax({
              type: "POST",
              url: semusiCommon.PANELURL + '/i/push/test',
              data: {
                  app_id: app_id,
                  did: did
              },
              dataType: "json",
              success: function (data) {
                  document.getElementById("push-result").innerHTML = JSON.stringify(data);
                  //$("#push-result").html(data);
              },
              error: function(xhr, error){
                  console.warn(xhr); console.warn(error);
                 // $("#push-result").html(data);
              },
          });
      })
  
      document.getElementById('submit-token').addEventListener('click', function(event) {
          event.preventDefault(); 
          let token = document.getElementById('update-pushToken').value;
          let did = document.getElementById('update-did').value;
  
         $.ajax({
              type: "POST",
              url: semusiCommon.API_PARTS.metrices.r + '/savePushToken',
              data: {
                   api_key: semusiCommon.getActiveUser.api_key,
                   app_id: semusiCommon.ACTIVE_APP_ID,
                   token:token,
                   did:did,
                  "uniqueNumber": semusiCommon.randomNumber(),
              },
              dataType: "json",
              success: function (data) {
              },
              error: function(xhr, error){
                  console.warn(xhr); console.warn(error);
              },
          });
      });
  
  
  
  
  }(window.RawUserData = window.RawUserData || {}, jQuery));
  