console.log("content page");
// chrome.runtime.onMessage.addListener((message, sender, senderResponse) => {
//   if (message.name === "stream" && message.streamId) {
//     console.log("stream");
//   }
// });

async function setDataDB(tbl, value, version) {
  try {
    let idb = indexedDB.open("wstracker_new_db", 1);
    idb.onsuccess = async () => {
      let res = idb.result;
      let tx = res.transaction(tbl, "readwrite");
      let store = tx.objectStore(tbl);
      const lastinsertdata = store.put(value);
      console.log(typeof lastinsertdata);
       
      setTimeout(() => {
        return lastinsertdata.result;
      }, 100);
      
    };
  } catch (err) {
    console.log("db error", err);
    return false;
  }
}
function senNotification() {
  chrome.notifications.create(
    "screenshot-taken",
    {
      type: "basic",
      iconUrl: "images/1.png",
      title: "WorkStatus",
      message: "Screenshot Taken!",
    },
    function (res) {
      console.log("Popup done!", res);
    }
  );
}

function sendTimeChangeNotification() {
  chrome.notifications.create(
    "time-changed",
    {
      type: "basic",
      iconUrl: "images/1.png",
      title: "WorkStatus",
      message: "A change in your system Date/Time has been detected  -  Workstatus extension will be stopped due to this. Please correct your system Date/Time in order to continue the Workstatus extension.",
    },
    function (res) {
      console.log("Time change Popup done!", res);
    }
  );
}

function setConfigDataTimerBg() {
  var totaldata = [];
  let idb = indexedDB.open("wstracker_new_db");
  idb.onsuccess = () => {
    let res = idb.result;
    let tx = res.transaction("totalTime", "readonly");
    let store = tx.objectStore("totalTime");
    let cursor = store.openCursor();
    cursor.onsuccess = () => {
      let curRes = cursor.result;
      if (curRes) {
        console.log("resssss", curRes.value);
        totaldata = curRes.value;
        //curRes.continue()
        console.log("finalData", totaldata);
        emptyStoreBG("totalTime");
        totaldata.start_time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
        setDataDB("totalTime", totaldata, 1);
      } else {
        totaldata = [];
      }
    };
     
  };
}

function setConfigDataTimerBgDateChange() {
  var totaldata = [];
  let idb = indexedDB.open("wstracker_new_db");
  idb.onsuccess = () => {
    let res = idb.result;
    let tx = res.transaction("totalTime", "readonly");
    let store = tx.objectStore("totalTime");
    let cursor = store.openCursor();
    cursor.onsuccess = () => {
      let curRes = cursor.result;
      if (curRes) {
        console.log("resssss", curRes.value);
        totaldata = curRes.value;
        //curRes.continue()
        console.log("finalData", totaldata);
        emptyStoreBG("totalTime");
        totaldata.start_time = moment().startOf('day').format('YYYY-MM-DD HH:mm:ss');
        setDataDB("totalTime", totaldata, 1);
      } else {
        totaldata = [];
      }
    };
     
  };
}

function setIntervaloldData(
  lastId,
  start,
  stop = "null",
  breakid = null,
  intervaldb = 5,
  ip_address = 0,
  itt
) {
  console.log("calling old activity")
  chrome.storage.local.get(["ip_address"]).then((ipaddressresult) => {
    ip_address = ipaddressresult.ip_address;
  chrome.storage.local.get(["latitude"]).then((latituderesult) => {
    lat = latituderesult.latitude;
  chrome.storage.local.get(["longitude"]).then((longituderesult) => {
    long = longituderesult.longitude;
    var intervaldata = {
      timer_data_id: lastId,
      from: start,
      to: stop,
      break_id: breakid,
      deviceType: "Windows",
      os_type: "Windows",
      file_size: "12312322",
      screenUrl: [],
      activityLevel: {
        mouse: "0",
        average: "0",
        keyboard: "0",
      },
      appAndUrls: [],
      location: {
        long: long,
        lat: lat,
      },
      note: null,
      interval_time_db: intervaldb,
      deviceId: "4C4C4544-0039-3110-804A-CAC04F4C5731LenovoVinove2",
      ip_address: ip_address,
      os_version: "Microsoft Windows 10 Home Single Language",
    };
    let istimeinsert = setDataDB("interval_data", intervaldata, 8);

    chrome.storage.local.get(["timer_obj"]).then((toresult) => {
      let timerobj = JSON.parse(toresult.timer_obj);
    for (const key in timerobj) {
      if(key == itt){
        timerobj[key] = 4;
      } 
    }
      let myJSON = JSON.stringify(timerobj);
      chrome.storage.local.set({ timer_obj: myJSON });
    });

  })
})
})
}

function setIntervalData(
  lastId,
  start,
  stop = "null",
  breakid = null,
  intervaldb = 5,
  ip_address = 0
) {
  chrome.storage.local.get(["ip_address"]).then((ipaddressresult) => {
    ip_address = ipaddressresult.ip_address;
  chrome.storage.local.get(["latitude"]).then((latituderesult) => {
    lat = latituderesult.latitude;
  chrome.storage.local.get(["longitude"]).then((longituderesult) => {
    long = longituderesult.longitude;
    var intervaldata = {
      timer_data_id: lastId,
      from: start,
      to: stop,
      break_id: breakid,
      deviceType: "Windows",
      os_type: "Windows",
      file_size: "123",
      screenUrl: [],
      activityLevel: {
        mouse: "0",
        average: "0",
        keyboard: "0",
      },
      appAndUrls: [],
      location: {
        long: long,
        lat: lat,
      },
      note: null,
      interval_time_db: intervaldb,
      deviceId: "4C4C4544-0039-3110-804A-CAC04F4C5731LenovoVinove1",
      ip_address: ip_address,
      os_version: "Microsoft Windows 10 Home Single Language",
    };
    let nextintervaltime = moment(stop).add(intervaldb * 60, 'seconds').format('DDHHmm');
    chrome.storage.local.set({ next_interval_time: nextintervaltime });
    let istimeinsert = setDataDB("interval_data", intervaldata, 8);
  })
})
})
}

function sendDatatoServer() {
  console.log("sendDatatoServer calling+++")
  const finalarr = [];
  return new Promise(function (resolve, reject) {
    console.log("create data for server");
    let idb = indexedDB.open("wstracker_new_db");
    idb.onsuccess = () => {
      let intervalarr = [];
      let res = idb.result;
      let tx = res.transaction("timer_data", "readwrite");
      let store = tx.objectStore("timer_data");
      let cursor = store.openCursor();
      cursor.onsuccess = () => {
        let curRes = cursor.result;
if(curRes){
        let curResval = curRes.value;
        let curReskey = curRes.key;
        if (typeof cursor.result.value.stop !== "undefined") {
          let stop_time = cursor.result.value.stop;
          // if (stop_time) {
          //   curRes.delete();
          // }
        }

        if (curResval) {
          console.log("curResval", curResval);
          let intervaltx = res.transaction("interval_data", "readwrite");
          let intervalstore = intervaltx.objectStore("interval_data");
          const myIndex = intervalstore.index("timerindx");
          const getRequest = myIndex.getAll(curReskey);
          let interValPromise = new Promise((_resolve, _reject) => {
            console.log('curRes.key',curRes.key)
            getRequest.onsuccess = () => {
              let intervalcurRes = getRequest.result;
               console.log("IntervalCurResp "+intervalcurRes);
              if (intervalcurRes) {
                intervalcurRes.forEach((item, index) => {
                  intervalarr[index] = item;
                });
                curResval.intervals = intervalarr;
                ////////////////////////////////////////////////

                //////////////////////////////////////
                _resolve(curResval);
                //    intervalarr = intervalarr;
              }
              // intervalcurRes.continue()
              // intervalcurRes.close();
            };
          });
          interValPromise.then((_res) => {
             console.log('__res__',_res);
            finalarr.push(_res);
            // curRes.value['intervals']=finalarr;
            // console.log('before curRes',curRes)
              console.log('finalArray',JSON.stringify(finalarr))
            const url =
            endpointUrl+"activity/log";
            ///////////////////////////////////////////////////////////

            chrome.storage.local.get(["userDetailChrome"]).then((result) => {
              // console.log('userDetailChrome',result.userDetailChrome.token);
              var ChromeSDToken = result.userDetailChrome.sd_token;
              var ChromeAuthorization = result.userDetailChrome.token;
              var ChromeOrgID = result.userDetailChrome.org_id;
              var ChromeUserID = result.userDetailChrome.id;

              const header = {
                SDToken: ChromeSDToken,
                Authorization: "Bearer " + ChromeAuthorization,
                OrgID: ChromeOrgID,
                "Content-Type": "application/json",
                UserID: ChromeUserID,
                deviceType: 'Chrome_extension'
              };
              // const header = {
              //     SDToken: "31512|uRW6nlgFa8W9vKcDGQiFDIOdFTNu7fI3eDeP3rHm",
              //     Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vYXBpLm5ld3N0YWdpbmcud29ya3N0YXR1cy5pby9hcGkvdjEvbG9naW4iLCJpYXQiOjE2NzU2NzQ5NTAsImV4cCI6MjE0ODcxNDk1MCwibmJmIjoxNjc1Njc0OTUwLCJqdGkiOiIxTjUzSUZVWTYwTUZPaGtYIiwic3ViIjoiMzEzNiIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.enjJqBIYCaQjIQMZVaMEZrhYzURH_xk8GjF2i-zfIQU",
              //     OrgID: 1238,
              //     'Content-Type': 'application/json',
              //     UserID: 3136
              //   }

              fetch(url, {
                method: "POST",
                headers: header,
                body: JSON.stringify(finalarr),
              }).then((res) => {
                ////////////////////delete master////////////////////////

                let idbdelm = indexedDB.open("wstracker_new_db");
                idbdelm.onsuccess = () => {
                  let resm = idbdelm.result;
                  let txm = resm.transaction("timer_data", "readwrite");
                  let storem = txm.objectStore("timer_data");
                  let cursorm = storem.openCursor();
                    cursorm.onsuccess = () => {
                      let curResm = cursorm.result;
                      if(curResm){
                        
                        let stop_time = cursorm.result.value.stop;
                         if (stop_time) {
                          curResm.delete();
                              }
                        console.log("deleted data id")
                      }
                    
                  };
                   
                };
                ///////////////////////////////////////////////
                ////////////////////////////////////////////
                let idbdel = indexedDB.open("wstracker_new_db");
                idbdel.onsuccess = () => {
                  let resdel = idbdel.result;
                  let txdel = resdel.transaction("interval_data", "readwrite");
                  let storedel = txdel.objectStore("interval_data");
                  const myIndexDel = storedel.index("timerindx");
                  //  const delRequest = myIndexDel.getAll(curRes.key);
                  let delRequest = myIndexDel.openCursor(curRes.key);
                  delRequest.onsuccess = () => {
                    let delcurRes = delRequest.result;
                    if (delcurRes) {
                      delcurRes.delete();
                      delcurRes.continue();
                    }

                    // if (delcurRes) {
                    //     delcurRes.forEach((item,index) => {
                    //         storedel.delete(index);
                    //      console.log('item index',index);
                    //     })
                    //   }
                  };
                   
                };

                ///////////////////////////////////////////////
                resolve("datasynced");
                console.log("Request complete! response:", res);
              });
            });
            ////////////////////////////////////////////////////
          });

          ////////////////////////////////////////
          //         console.log('before begguer',intervalarr)
          //    console.log('intervalarr new',intervalarr);
          // console.warn(curRes.value, 'wsjgsss');

          // curRes.value.intervals = intervalarr;
          // console.log('finalarr before push',finalarr)
          // finalarr.push(curRes.value);
          // console.log('sdkjfhkjh>>>',finalarr,curRes.value);

          //  curRes.continue()

          ///////////////////////////////////////////////////////
          // const url = "https://api.newstaging.workstatus.io/api/v1/activity/log";
          // let retriveItem = JSON.parse(localStorage.getItem("userDetail"));
          //     const data = {
          //         finalarr
          //    };
          // const header = {
          //   SDToken: "31512|uRW6nlgFa8W9vKcDGQiFDIOdFTNu7fI3eDeP3rHm",
          //   Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vYXBpLm5ld3N0YWdpbmcud29ya3N0YXR1cy5pby9hcGkvdjEvbG9naW4iLCJpYXQiOjE2NzU2NzQ5NTAsImV4cCI6MjE0ODcxNDk1MCwibmJmIjoxNjc1Njc0OTUwLCJqdGkiOiIxTjUzSUZVWTYwTUZPaGtYIiwic3ViIjoiMzEzNiIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.enjJqBIYCaQjIQMZVaMEZrhYzURH_xk8GjF2i-zfIQU",
          //   OrgID: 1238,
          //   'Content-Type': 'application/json',
          //   UserID: 3136
          // }
          //      $.ajax({
          //       type: "POST",
          //       contentType: "application/json; charset=utf-8",
          //       url: url,
          //       data: JSON.stringify(data),
          //       headers: header,
          //       success: function (result) {
          //         if(result.response.code!='200'){
          //             console.log('sync status',result.response.message);
          //         }
          //         else{
          //             console.log('sync status','error');
          //         }
          //       }
          //   });

          resolve("datasynced");
        } else {
          reject(Error("Error text"));
        }
      }
      
      };
      
    };
  });
}

function emptyStoreBG(storeName) {
  let idb = indexedDB.open("wstracker_new_db", 1);
  idb.onsuccess = async () => {
    let res = idb.result;
    let tx = res.transaction(storeName, "readwrite");
    let store = tx.objectStore(storeName);
    const lastinsertdata = store.clear();
    console.log(typeof lastinsertdata);
     
    console.log("deleted");
    
  };
}

function SyncedData(todayDate) {
  emptyStoreBG("syncTimer");
  chrome.storage.local.get(["userDetailChrome"]).then((result) => {
    // console.log('userDetailChrome',result.userDetailChrome.token);
    var ChromeSDToken = result.userDetailChrome.sd_token;
    var ChromeAuthorization = result.userDetailChrome.token;
    var ChromeOrgID = result.userDetailChrome.org_id;
    var ChromeUserID = result.userDetailChrome.id;

    const header = {
      SDToken: ChromeSDToken,
      Authorization: "Bearer " + ChromeAuthorization,
      OrgID: ChromeOrgID,
      "Content-Type": "application/json",
      UserID: ChromeUserID,
      deviceType: 'Chrome_extension'
    };
    let postData = {
      date: todayDate,
      tracker: 1,
    };
    const url = endpointUrl+"activity/syncTimer";
    fetch(url, {
      method: "POST",
      headers: header,

      body: JSON.stringify(postData),
    })
      .then((res) => {
        return res.json();
      })
      .then((result) => {
        console.log("result new", result.response);
        if (result.response.code != "200") {
          console.log(result.data);
         // console.warn(result.response.message);
        } else {
          let last_synced = moment().format("YYYY-MM-DD HH:mm:ss");
          chrome.storage.local.set({ last_synced: last_synced });
          console.log(result.response.message);
          result.response.data.forEach((item) => {
            console.log("sync timer item", item);
            setDataDB("syncTimer", item, 2);
            
          });
        }
        //     ////////////////////////////////////////////
        //     let idbdel = indexedDB.open('wstracker_new_db')
        //     idbdel.onsuccess = () => {
        //         let resdel = idbdel.result;
        //         let txdel = resdel.transaction('syncTimer','readwrite');
        //         let store = txdel.objectStore('syncTimer');
        //     let Requestdate = store.openCursor()
        //     Requestdate.onsuccess = () => {
        //           let curRes = Requestdate.result;
        //           console.log('Requestdate.result',Requestdate.result);
        //           if(curRes){
        //             curRes.response.data.forEach( item => {
        //     setDataDB('syncTimer',item,2);
        // })

        //           }
        //         };
        //     }
        ///////////////////////////////////////////////
      });
  });
}


function setConfigDataTimerStopBG() {
  var totaldata = [];
  let idb = indexedDB.open("wstracker_new_db");
  idb.onsuccess = () => {
    let res = idb.result;
    let tx = res.transaction("totalTime", "readonly");
    let store = tx.objectStore("totalTime");
    let cursor = store.openCursor();
    cursor.onsuccess = () => {
      let curRes = cursor.result;
      if (curRes) {
        console.log("resssss", curRes.value);
        totaldata = curRes.value;
        //curRes.continue()

        emptyStoreBG("totalTime");
        // totaldata.start_time = getCurrentDateTime();
        // setUserdata('totalTime',totaldata,1)
      } else {
        totaldata = [];
      }
    };
    
  };
}


function setTimerDBStopBG() {
  let currentTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
  chrome.storage.local.get(["lastID"]).then((result) => {
    let lastdataid = result.lastID;
    console.log('lastdataidlastdataid',lastdataid)
    let idb = indexedDB.open("wstracker_new_db");
    idb.onsuccess = () => {
      let res = idb.result;
      let tx = res.transaction("timer_data", "readwrite");
      let store = tx.objectStore("timer_data");
      let cursor = store.get(lastdataid);
      let cursorPromise = new Promise((_resolve, _reject) => {
        cursor.onsuccess = () => {
          let curRes = cursor.result;
          console.log('AAAAA'+curRes);
          if (curRes) {
            console.log('BBBBB');
            data = curRes;
            data.stop = currentTime;
            const updateRequest = store.put(data, lastdataid);
            //////////////////////////////////////////// 
          }
         
          
        };
      });
      cursorPromise.then((oldts) => {
         console.log('Time changed & db updated')
      });
       
    };
  });
}

function setTimerDBStopBGNew() {
  console.log('IIIII');
  let oldts = 0;
  let pid = $("#project_id").val();
  console.log("ProjectIDS-"+pid);
  let tid = $("#task_id").val() > 0 ? $("#task_id").val() : null;
  let currentTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
  chrome.storage.local.get(["lastID"]).then((result) => {
    let lastdataid = result.lastID;
    console.log("lastdataid update", lastdataid);
    let idb = indexedDB.open("wstracker_new_db");
    idb.onsuccess = () => {
      let res = idb.result;
      let tx = res.transaction("timer_data", "readwrite");
      let store = tx.objectStore("timer_data");
      let cursor = store.get(lastdataid);
      let cursorPromise = new Promise((_resolve, _reject) => {
        cursor.onsuccess = () => {
          let curRes = cursor.result;
          if (curRes) {
            console.log("old data", curRes);
            data = curRes;
            data.stop = currentTime;
            const updateRequest = store.put(data, lastdataid);
            ////////////////////////////////////////////
            let idbdel = indexedDB.open("wstracker_new_db");
            idbdel.onsuccess = () => {
              let resdel = idbdel.result;
              let txdel = resdel.transaction("syncTimer", "readwrite");
              let storedel = txdel.objectStore("syncTimer");
              // const myIndexDel = storedel.index("projectidindx");
              //  const delRequest = myIndexDel.getAll(curRes.key);
              let delRequest = storedel.openCursor();
              delRequest.onsuccess = () => {
                let delcurRes = delRequest.result;
                if (delcurRes) {
                  console.log("delcurRes", delcurRes.value.projectId);
                  if (
                    delcurRes.value.projectId == pid &&
                    delcurRes.value.todoId == tid
                  ) {
                    oldts = delcurRes.value.timeLog;
                    delcurRes.delete();
                  }
                  delcurRes.continue();
                }
                console.log("oldts from prommise", oldts);
                _resolve(oldts);
              };
            };
          }
          ///////////////////////////////////////////////
          // let startTime=moment(data.start);
          // let ct=moment(currentTime);
          // let tsec = ct.diff(startTime, 'seconds');
          // let newData = {
          //   "projectId": pid,
          //   "todoId": tid,
          //   "timeLog": tsec + oldts
          // }
          // setUserdata('syncTimer',newData,2)
          ////////////////////////////////////////////
          chrome.storage.local.get(["start_time"]).then((startTimeresult) => {
            if (startTimeresult.start_time) {
              var startbeforeStop = startTimeresult.start_time;
            } else {
              var startbeforeStop = data.start;
            }
            createIntervalData(
              lastdataid,
              startbeforeStop,
              currentTime,
              (breakid = null),
              data.interval_time,
              0
            );

          });
          //////////////////////////////////////////////
          
        };
      });
      cursorPromise.then((oldts) => {
        console.log("oldts after prommmise", oldts);
        let startTime = moment(data.start);
        let ct = moment(currentTime);
        let tsec = ct.diff(startTime, "seconds");
        let newData = {
          projectId: pid,
          todoId: tid,
          timeLog: parseInt(tsec) + parseInt(oldts),
          added_by: "local"
        };
        console.log("tsec + oldts", tsec + oldts);
        setUserdata("syncTimer", newData, 2);
      });
    };
  });
}


function timeChanged(delta) {
  chrome.storage.local.set({ time_changed: 1 });
//  setTimerDBStopBG();
  //setConfigDataTimerStopBG();
  //stopTimerNow();
  
 
}

function setConfigDataTimerStopBGNew() {
  var totaldata = [];
  let idb = indexedDB.open("wstracker_new_db");
  idb.onsuccess = () => {
    let res = idb.result;
    let tx = res.transaction("totalTime", "readonly");
    let store = tx.objectStore("totalTime");
    let cursor = store.openCursor();
    cursor.onsuccess = () => {
      let curRes = cursor.result;
      if (curRes) {
        console.log("resssss", curRes.value);
        totaldata = curRes.value;
        //curRes.continue()

        emptyStore("totalTime");
        // totaldata.start_time = getCurrentDateTime();
        // setUserdata('totalTime',totaldata,1)
      } else {
        totaldata = [];
      }
    };
  };
}

function stopTimerNow() {
  console.log('Debugmore:::-');
  try{
    console.log("XYZ-");
    //$(".loader").show();
  json(endpointUrl+`getCurrentTime?timezone=Asia/Kolkata`).then(timerdata => {
    if(timerdata.response.code == 200){
  //////////////////////////////////////////
      console.log("UUUUU-UUUUU-"+timerdata.response.code);
  removeAlarm("start_timer");
  //$("#start").show();
  //$("#stop").hide();
  setTimerDBStopBGNew();
  setConfigDataTimerStopBGNew();
  clearTimeout(TimerInterval);
//  clearTimeout(TimerIntervalAll);
stopInterval("TimerIntervalAll")
  setTimeout(() => {
    console.log("stop requested")
    ////////////////////////////////////////////////
    let idb = indexedDB.open("wstracker_new_db");
    idb.onsuccess = () => {
      let res = idb.result;
      let tx;
      try{
       tx = res.transaction("timer_data", "readwrite");
      }
      catch(e) {
        window.location.href = "projectList.html";
      }
      let store = tx.objectStore("timer_data");
      let countRequest = store.count();
      countRequest.onsuccess = () => {
        console.log("total pending data",countRequest.result);
    let remaningdatacount = countRequest.result;
    console.log("remaningdatacount",remaningdatacount)
    for(let i = 0; i<countRequest.result; i++){
    
      sendDatatoServer().then((res) => {
        console.log("data syncedZZZZ " + i);
        // SyncedData(moment().format("YYYY-MM-DD"),0);
        ///////////////////////////////////////
      });
      remaningdatacount--;
    }
    if(remaningdatacount==0){
      setTimeout(() => {
        SyncedData(moment().format("YYYY-MM-DD"),0);
      }, 1000);
      
      setTimeout(() => {
        //$("#logout").show();
        $(".selection-dropdown-box").css("pointer-events", "");
        window.location.href = "projectList.html";
      }, 2000);
    }
    // sendDatatoServer().then((res) => {
    //   SyncedData(moment().format("YYYY-MM-DD"),0);
    //   setTimeout(() => {
    //  window.location.href = "projectList.html";
    // }, 3000);
    // });
  }
  countRequest.oncomplete = () =>{
    console.log("completeddddd1111")
    SyncedData(moment().format("YYYY-MM-DD"),0);
    setTimeout(() => {
      //$("#start").hide();
      //$("#logout").show();
      //$(".selection-dropdown-box").css("pointer-events", "");
     // window.location.href = "projectList.html";
    }, 1000);
  }
}
    /////////////////////////////////////////////
    
   }, 2000);
   //////////////////////////////////
  }
  else{
    // $("#perror").html(
    //   "<b style='color:red'>Please connect to internet</b>"
    // );
  }
})
.catch((error) => {
  // $("#perror").html(
  //   "<b style='color:red'>Please connect to internet</b>"
  // );
});
} catch (err) {
  console.log("CATCH-"+ err);
  // $("#perror").html(
  //   "<b style='color:red'>Please connect to internet</b>"
  // );
}
}

function json(url) {
  return fetch(url).then((res) => res.json());
}

function removeAlarm(name) {
  chrome.alarms.clear(name);
}

function stopInterval(intervalID){
  clearInterval(TimerIntervalAll);
}