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


function cdatetime(){
  var d = new Date($.now());
// return d.getDate()+"-"+(d.getMonth() + 1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

return d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
}
function setTimerDB(){
  let retriveItem = JSON.parse(localStorage.getItem("userDetail"));

  var projectid = $('#project_id').val();
  var taskid = $('#task_id').val();
  console.log('projectid',projectid);
if(parseInt(projectid)>0){
  try{
   let checktimerdata = false;
//  let istimeset = setTimer();
// var timerdata = [];
let ip_address = 0;
let apiKey = 'ed5e95c005f0103f9c62fa9b97c591965ebf9e0e90dabd2da7bd2820';
json(`https://api.ipdata.co?api-key=${apiKey}`).then(data => {
  console.log(data.ip);
  ip_address = data.ip;
});

var intervaldata = {
    "timer_data_id": 45,
    "from": cdatetime(),
    "to": "null",
    "break_id": null,
    "deviceType": "Windows",
    "os_type": "Windows",
    "file_size": "null",
    "screenUrl": [
        "https://workstatus.s3.amazonaws.com/128/3710/screenshot/202301160553481.jpg"
    ],
    "activityLevel": {
        "mouse": "0",
        "average": "0",
        "keyboard": "0"
    },
    "appAndUrls": [],
    "location": {
        "long": "75.7105",
        "lat": "26.9525"
    },
    "note": null,
    "interval_time_db": "10",
    "deviceId": "4C4C4544-0039-3110-804A-CAC04F4C5731Lenovo",
    "ip_address": ip_address,
    "os_version": "Microsoft Windows 10 Home Single Language"

};
var timermaindata = {
  "projectId": $('#project_id').val(),
  "start": cdatetime(),
    "stop": null,
    "selfi_id": "0",
    "break_id": null,
    "deviceType": "Windows",
    "os_type": "Windows",
    "time_type": "1",
    "selfiVerification": "false",
    "interval_time": "10",
    "source_type": "4",
    "org_id": retriveItem.org_id,
    "todo_id": taskid,
    "deviceId": "4C4C4544-0039-3110-804A-CAC04F4C5731Lenovo",
    "ip_address": ip_address,
    "os_version": "Microsoft Windows 10 Home Single Language"
}

// timermaindata.intervals.push(intervaldata);
// timerdata.push(timermaindata);
checktimerdata = setTimer(timermaindata);
if(checktimerdata){
  setIntervalData(intervaldata,checktimerdata);
  return true;
 }
  else{
    $("#perror").html("<b style='color:red'>Something went wrong</b>");

  }
 
}
catch(err){
console.log('err',err);
 
}
///////////////////////////////////////////////

}
else{
  $("#perror").html("<b style='color:red'>Please select a project</b>");
}
  
}

 function setTimer(timerdata){
  // var jsontimerdata = JSON.stringify(timerdata);
 let istimeinsert =  setUserdata('timer_data',timerdata,7);
console.log('insidefunc',istimeinsert);
if(istimeinsert){
return true;
}
 else{
  return false;
 }
}
function setIntervalData(timerdata,lastid){
  timerdata.timer_data_id = lastid;
 let istimeinsert = setUserdata('interval_data',timerdata,8);
 
if(istimeinsert){
return true;
}
 else{
  return false;
 }
}
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = decodeURIComponent(hash[1]);
    }
    return vars;
}
function setSelectedData(){
  let paramval = getUrlVars();
  
  $("#projectdata").html("<b>Project:</b> "+paramval.projectname);
  $("#project_id").val(paramval.pid);
  
  if(paramval.taskid>0){
    $("#taskdata").html("<b>Task: </b>"+paramval.taskname);
    $("#task_id").val(paramval.taskid);
    
  }
  

  console.log(paramval);
}
setSelectedData();

var hours =0;
var mins =0;
var seconds =0;

$('#start').click(function(){
    $('#start').hide();
    $('#stop').show();
      startTimer();
      setTimerDB();
});

$('#stop').click(function(){
    $('#start').show();
    $('#stop').hide();
      clearTimeout(timex);
});

// $('#reset').click(function(){
//       hours =0;      mins =0;      seconds =0;
//   $('#hours','#mins').html('00:');
//   $('#seconds').html('00');
// });

function startTimer(){
  timex = setTimeout(function(){
      seconds++;
    if(seconds >59){seconds=0;mins++;
       if(mins>59) {
       mins=0;hours++;
         if(hours <10) {$("#hours").text('0'+hours+':')} else $("#hours").text(hours+':');
                       }
                       
    if(mins<10){                     
      $("#mins").text('0'+mins+':');}       
       else $("#mins").text(mins+':');
                   }    
    if(seconds <10) {
      $("#seconds").text('0'+seconds);} else {
      $("#seconds").text(seconds);
      }
     
    
      startTimer();
  },1000);
}
    
async function setUserdata(tbl,value,version){
  try{
    
  let idb = indexedDB.open('wstracker_new_db', version)
  idb.onupgradeneeded = () => {
      let res = idb.result;
      const objectStore = res.createObjectStore(tbl, { autoIncrement: true });
      if(tbl=='interval_data'){
        objectStore.createIndex('timerindx','timer_data', {unique : false});
      }
      if(tbl=='timer_data'){
        objectStore.createIndex('todoindx','todo_id', {unique : false});
        objectStore.createIndex('projectindx','projectId', {unique : false});
        objectStore.createIndex('breakidindx','break_id', {unique : false});
      }
      

  }
  idb.onsuccess = () => {
      let res = idb.result;
      let tx = res.transaction(tbl, 'readwrite')
      let store = tx.objectStore(tbl)
      let insertdata = store.put(value)
      res.close()
      console.log('insertid',insertdata);
      return insertdata.result;
}
 
}
catch(err){
  console.log('db error',err);
}
return false;
}




