// needed for instantiation of ipfs
 const initIPFS = async (IPFS, ORBITDB) => {

  // Create IPFS instance
 // const ipfsOptions = { repo: '/orbitdb/examples/browser/new/ipfs/0.33.1', }
  //const ipfs = await Ipfs.create(ipfsOptions)

  // Create OrbitDB instance
  //const orbitdb = await OrbitDB.createInstance(ipfs)

}
initIPFS()
async function createDb(){
  const ipfs = await Ipfs.create({repo: 'ok' + Math.random()}); 

// Create database instance
 const orbitdb = await OrbitDB.createInstance(ipfs)
 //const ipfsOptions = { repo: '/orbitdb/createdb1', }

 const db = await orbitdb.keyvalue('routes')
                const address = db.address
                //console.log(address)
                //console.log(db.address.toString())
                await db.put('2022-07-01T10:49:07', '49.41185089/8.67646861',{pin: true})
                await db.put('2022-07-01T10:49:12', '49.41166303/8.67652893')
                await db.put('2022-07-01T10:49:20','49.41123636/8.67652849')
                await db.put('2022-07-01T10:49:25','49.41084041/8.67651128')
                await db.put('2022-07-01T10:49:31','49.41049801/8.67656948')
                await db.put('2022-07-01T10:49:38','49.4102198/8.67658131')
                await db.put('2022-07-01T10:49:44','49.40982577/8.67668618')
                await db.put('2022-07-01T10:49:50','49.4095211/8.6767495')
                await db.put('0000','00/00');
                await db.put('2022-07-01T10:56:43','49.39117231/8.68814905')
                await db.put('2022-07-01T10:56:50','49.39076199/8.68818273')
                await db.put('2022-07-01T10:56:59','49.39058452/8.68776805')
                await db.put('2022-07-01T10:57:04','49.39048152/8.68746322')
                await db.put('2022-07-01T10:57:10','49.39009475/8.68742468')
                await db.put('2022-07-01T10:57:18','49.38966856/8.68741891')
                await db.put('2022-07-01T10:57:26','49.3896966/8.68683682')
                await db.put('2022-07-01T10:57:34','49.38985798/8.68647962')
                await db.put('2022-07-01T11:00:12','49.38983544/8.68654936')
                await db.put('2022-07-01T11:00:19','49.38982943/8.68686349')
                await db.put('2022-07-01T11:00:24','49.38988557/8.68711804')
                await db.put('2022-07-01T11:00:32','49.38975355/8.68742027')
                await db.put('2022-07-01T11:00:39','49.38968475/8.68789061')
                await db.put('2022-07-01T11:00:47','49.38968741/8.68864464')
                await db.put('2022-07-01T11:00:56','49.38981096/8.68935897')
                await db.put('2022-07-01T11:01:03','49.38991498/8.6898232')
                await db.put('2022-07-01T11:01:13','49.39008687/8.69005123')
                await db.put('2022-07-01T11:01:20','49.39012705/8.69004198')
                await db.put('2022-07-01T11:01:42','49.39012273/8.69044973')
                await db.put('2022-07-01T11:03:13','49.39020013/8.69013153')
                await db.put('2022-07-01T11:03:37','49.3902416/8.69011779')
                await db.put('2022-07-01T11:06:03','49.39010871/8.68987621')
                let csv = "./new.csv"
                const value = db.all
              //console.log(value)
                console.log('database connected!')
              //console.log(value)
                await db.close()
                return db
               }

               async function loadRoute(){
                const db = await createDb()
                await db.load()
                console.log("loadroute ausgeführt")
                const value = db.all 
                //console.log(value)
                return value;
              }
              async function connectDB(){
               //const ipfsOptions = { repo: '/orbitdb/los', }
                //const ipfs = await Ipfs.create(ipfsOptions)
                const ipfs = await Ipfs.create()
                const orbitdb = await OrbitDB.createInstance(ipfs)
                const db_route2 = await orbitdb.open('/orbitdb/zdpuApZ7pMKupZjmxPQk8xp34QdAEXHFFjmA3EPWuACN88DwB/coordinates');
                  //const route2 = db_route2.all
                  //console.log(OrbitDB.isValidAddress('/orbitdb/zdpuAqETvwNibieag6o5ahX4d6WKXi6QZvbar3XZPJEXz3vSE/coordinates'));
                 //console.log(db_route2.all);
                  //console.log(db_route2.address.toString())
                  return db_route2;
              }
              async function getCurrentCoordinate(){
                var db_conn = await createDb()
                const currentCoordinate = db_conn.all
                //console.log(currentCoordinate)
                var latest_coord_string = (currentCoordinate[Object.keys(currentCoordinate)[Object.keys(currentCoordinate).length - 1]])
                var latest_coordinate_str = latest_coord_string.split("/")
                latest_coordinate_str[0] = parseFloat(latest_coordinate_str[0])
                latest_coordinate_str[1] = parseFloat(latest_coordinate_str[1]) 
                //console.log(latest_coordinate_str)
              
                return latest_coordinate_str;
              }
              
              async function getCurrentTime(){
              
                var db_conn = await createDb()
                const currentCoordinate = db_conn.all
                //console.log(currentCoordinate)
                var all_times = (Object.keys(currentCoordinate))
                var lasttime = all_times[(all_times.length-1)] 
                //console.log(lasttime)
                return lasttime;
              }
              
              var buffer_for_i = 0;
              async function getAllCoordinates(){
              var db2 = await createDb()
              const current_route = db2.all
              // coordinates in this schema 49.123/8.2311
              var coordinates = Object.values(current_route)
              // parse to string for split and then split by / 
              var coordinate_string = coordinates.toString()
              var between_string = coordinate_string.split("/")
              var final_string = between_string.toString()
              //comma string looks now like this : 49.1212,8.1231,49.1231, ...
              const comma_string = final_string.split(',')
              // create new Array and put string back in to array for using paths/polylines with leafleat
              var route0 =[];
              var route1 = []
              // use for loop for iterating over string and put it in the right order
              //route 0
              for (var i = 0; i < comma_string.length; i++) {
                //console.log(comma_string[i])
                if (comma_string[i] == "00"){
                  console.log("00 gefunden")
                  buffer_for_i = i +2;
                  //console.log(buffer_for_i)
                  break;
                }
                route0.push([comma_string[i], comma_string[i+1]])
                i = i+1       
              }
               // its only for converting the string array to a float array, because leaflethjs wants only a float array 
              (function(elem) {
              var callee = arguments.callee;
                return elem instanceof Array ? elem.map(function(elem2) { return callee(elem2); })
                                             : parseFloat(elem);
              })
              route0 = route0.map(function(elem) {
                return elem.map(function(elem2) {
                    return parseFloat(elem2);
                });
              });
              //console.log("route0")
              //console.log(route0)
              //route 1
              for (var i = buffer_for_i; i < comma_string.length; i++) {
                console.log(buffer_for_i)
                if (comma_string[i] == "00"){
                  //console.log("00 gefunden")
                  //console.log(buffer_for_i)
                  break;
                }else if(comma_string[i] == "11"){
                  noroutes = 1;
                  //console.log("Ende gefunden")
                }
                route1.push([comma_string[i], comma_string[i+1]])
                i = i+1        
              }
              //console.log("route1")
              //console.log(route1)
               // its only for converting the string array to a float array, because leaflethjs wants only a float array 
              (function(elem) {
              var callee = arguments.callee;
                return elem instanceof Array ? elem.map(function(elem2) { return callee(elem2); })
                                             : parseFloat(elem);
              })
              route1 = route1.map(function(elem) {
                return elem.map(function(elem2) {
                    return parseFloat(elem2);
                });
              });
              
              //console.log(route)
              return [route0, route1];
              }

async function createRouteObject(){              
              var currentime = await getCurrentTime()
              var myBtn = document.createElement("p");
              myBtn.innerHTML = "<ul><li><div><h4 >Last traveled Route</h4><div><p>" +currentime+"</p></div></div></li></ul>";
              document.ul.appendChild(myBtn); 
}           
async function createlistitem() {
    var currentime = await getCurrentTime();
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    li.appendChild(document.createTextNode("Last travelled route on: "   +currentime+""));
    ul.appendChild(li);
}

