

let scene = document.querySelector('a-scene'),
camera = document.querySelector('a-camera'),
yRotation = document.querySelector('#y-rotation'),

start = {lat: 22.364563, lon: 113.600967},
end = {lat: 22.363379, lon: 113.598615},
route = [],
path = {},
pathRecord = [],
pathCreated = false;

window.addEventListener('update-heading', function(data) {
  yRotation.innerText = Math.floor(data.detail) + "°";
});



// if this is not accurate we need to hook it onto camera.tick
window.addEventListener('gps-camera-update-position', function(data) {
  // console.log('gps-camera-update-position', data);

  let cameraPosition = [data.detail.position.latitude, data.detail.position.longitude];

  // if(route.length > 1) {
  //   route[0] = cameraPosition;
  // }

  if(pathCreated) {
    // update path
  } else if(!pathCreated && route.length > 1) {
    // put camera position at route[0]
    route[0] = cameraPosition;
    path = createPath(route);
  }
});

window.addEventListener('gps-position-update', function(position) {
  // console.log(position);
});

// function createPathRoot(position) {
//   let root = document.createElement('a-curve-point');
//   root.setAttribute('gps-entity-place', `latitude: ${lat}; longitude: ${lon};`);
//   path.appendChild(curvePoint);
// }

function getRoute(start, end) {
  axios.get('https://dev.virtualearth.net/REST/v1/Routes/Walking', {
    params: {
      'wayPoint.1':      `${start.lat},${start.lon}`,
      'wayPoint.2':      `${end.lat},${end.lon}`,
      'routeAttributes': 'routePath',
      'key':             'Ahwqh1mUNte20qOAphNKU-hSGsmEnavPTOU-749M7MJl7MYIdsTmL4XFoSwS4QvP'
    }
  }).then(response => {
    if(response.status === 200) {
      route = response.data.resourceSets[0].resources[0].routePath.line.coordinates;
      
      // drawPath(route);
    } else {
      throw new Error(response.status);
    }
  })
}

function createBoxes(route) {
  if(route.length) {
    console.log(route);
    route.forEach(coordinate => {
      const lat = coordinate[0];
      const lon = coordinate[1];

      const placeText = document.createElement('a-box');
      placeText.setAttribute('gps-entity-place', `latitude: ${lat}; longitude: ${lon};`);
      // placeText.setAttribute('title', 'PATH');
      placeText.setAttribute('scale', '5 5 5');

      scene.appendChild(placeText);
    });    
  }
}

function createPath(route) {

  let path = {}; // null

  if(route.length > 1) {

    const pathElement = document.createElement('a-curve');
    pathElement.id = 'path';
    scene.appendChild(pathElement);
    path.el = pathElement;
    path.points = [];

    route.forEach(coordinate => {
      const lat = coordinate[0];
      const lon = coordinate[1];

      let pointElement = document.createElement('a-curve-point');
      pointElement.setAttribute('gps-entity-place', `latitude: ${lat}; longitude: ${lon};`);

      pathElement.appendChild(pointElement);

      path.points.push({el: pointElement, lat: lat, lon: lon});
    });
    

    // const drawPath = document.createElement('a-draw-curve');
    // drawPath.setAttribute('curveref', '#path');
    // drawPath.setAttribute('material', 'shader: line; color: green;');
    // scene.appendChild(drawPath);

    const renderElement = document.createElement('a-entity');
    renderElement.setAttribute('clone-along-curve', 'curve: #path; spacing: 2; scale: 1 1 1; rotation: 90 0 0;');
    renderElement.setAttribute('geometry', 'primitive:triangle;');
    renderElement.setAttribute('material', 'side: double; color: green;');
    scene.appendChild(renderElement);

    path.renderEl = renderElement;
    pathCreated = true;
  }

  return path;
}


function showPosition() {
  let lat = document.getElementById('latitude');
  let lon = document.getElementById('longitude');

  let options = {
    enableHighAccuracy: true,
    timeout: 30000,
    maximumAge: 0
  };
  
  function success(pos) {
    let crd = pos.coords;
    
    lat.innerHTML = `${crd.latitude}`;
    lon.innerHTML = `${crd.longitude}`;
  }
  
  function error(err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
  }
  
  navigator.geolocation.watchPosition(success, error, options);
}

showPosition();

// console.log(coordtransform.wgs84togcj02(113.59573843475094, 22.36707700088935));
getRoute(start, end);


// wgs84 gps position: 22.36707700088935, 113.59573843475094
// gcj02 gps position: 22.370123789469808, 113.5907111095581
