<template>
  <div id="contents">
    <!-- <h2 v-if="shown_idx != -1">Trajectory of {{ all_data[shown_idx].name }}</h2> -->
    <MyMap
      ref="mymap"
      :trajectories="currentTrajectory"
      :color-map="d3ColorMap"
      :color-map-img="colorMapImg"
    />
    <!-- <button id="btn-change" @click="changeData">Change data</button> -->
  </div>
</template>

<script>
import MyMap from '@/components/Map.vue'
import * as d3 from 'd3'
import mockdata from '../../../datasets/geojson.js'

export default {
  name: 'App',
  components: {
    MyMap
  },
  props: {
    instanceId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      //shown_idx: -1,
      d3ColorMap: d3.interpolateRdYlGn,
      colorMapImg: 'https://raw.githubusercontent.com/d3/d3-scale-chromatic/master/img/RdYlGn.png'
    }
  },
  computed: {
    currentTrajectory: function() {
      return mockdata.geojson
    }
  },

  mounted() {
    //this.changeData()
    //this.load_data();
    //this.load();
    //this.parseGeoJSON();
    //this.loadGeoJSON()
  },
  methods: {
    parse_csv(data) {
      console.log('Parsing')
      var date = new Date()

      this.all_data = global.d3.csv(data, () => {
        //global.noise.seed(Math.random());
        console.log('data', data)

        // generate a random trajectory with time data as a geojson object
        //let l = 0;
        let name = data[0].name.split(',')[0].split('(')[0]

        let geojson_list = []

        let geojson = {
          type: 'FeatureCollection',
          features: [
            {
              type: 'Feature',
              properties: {
                name: name + '_' + 0,
                time: []
              },
              geometry: {
                coordinates: [],
                type: 'LineString'
              }
            }
          ]
        }

        for (let d = 0; d < data.length; d++) {
          let time = date.getTime() + Math.round(Math.random() * 10000) + (d + 1) * 1000
          let current_lat = parseFloat(data.lat)
          let current_lon = parseFloat(data.lon)

          geojson['features'][0]['properties']['time'].push(time)
          geojson['features'][0]['geometry']['coordinates'].push([current_lon, current_lat])
        }

        geojson_list.push(geojson)

        // save it
        return {
          id: parseInt(data[0].id),
          name: data[0].name,
          lat: parseFloat(data[0].lat),
          lon: parseFloat(data[0].lon),
          geojson: geojson_list
        }
      })

      console.log('Parsed', this.all_data)
    },

    parse_csv_using_noise(data_text) {
      console.log('Parsing')
      var date = new Date()

      this.all_data = global.d3.csvParse(data_text, d => {
        global.noise.seed(Math.random())

        // generate a random trajectory with time data as a geojson object

        let name = d.name.split(',')[0].split('(')[0]

        let geojson_list = []

        for (var l = 0; l < 4; l++) {
          let time = date.getTime() + Math.round(Math.random() * 10000) + (l + 1) * 1000
          let current_lat = parseFloat(d.lat)
          let current_lon = parseFloat(d.lon)

          let geojson = {
            type: 'FeatureCollection',
            features: [
              {
                type: 'Feature',
                properties: {
                  name: name + '_' + l,
                  time: []
                },
                geometry: {
                  coordinates: [],
                  type: 'LineString'
                }
              }
            ]
          }

          for (var i = 0; i < 30; i++) {
            current_lat +=
              (global.noise.simplex2(1, i / 6.0) * 0.01 * (l + 1)) / 2 - (0.005 * (l + 1)) / 3
            current_lon +=
              (global.noise.simplex2(i / 6.0, 1) * 0.01 * (l + 1)) / 2 - (0.005 * (l + 1)) / 3

            if (i < 29) {
              time += Math.round(Math.random() * 100000) + 50000 * (l + 1)
            } else {
              time += Math.round(Math.random() * 100000) + 5000000 * (l + 1)
            }

            geojson['features'][0]['properties']['time'].push(time)
            geojson['features'][0]['geometry']['coordinates'].push([current_lon, current_lat])
          }

          geojson_list.push(geojson)
        }

        // save it
        return {
          id: parseInt(d.id),
          name: name,
          lat: parseFloat(d.lat),
          lon: parseFloat(d.lon),
          geojson: geojson_list
        }
      })

      console.log('Parsed', this.all_data)
    },

    load_data() {
      var client = new XMLHttpRequest()
      var data_text = ''
      // client.open('GET', '/data/MOCK_DATA.csv');
      // client.open('GET', '/data/JOJO_MOCK_DATA.csv');
      client.open('GET', 'https://lordnene.github.io/MockData/GEOJSON_BRNO.json')
      client.onreadystatechange = () => {
        if (client.responseText.length != 0 && this.all_data.length == 0) {
          data_text = client.responseText
          // this.parse_csv_using_noise(data_text);
          this.all_data = JSON.parse(data_text)
        }
      }
      client.send()
    },

    load() {
      console.log('Parsing')
      var date = new Date()

      this.all_data = d3
        .csv('/data/JOJO_MOCK_DATA.csv')
        .then(data => {
          //global.noise.seed(Math.random());
          console.log('data', data)

          // generate a random trajectory with time data as a geojson object
          //let l = 0;
          let name = data[0].name //.split(",")[0].split("(")[0];

          console.log('n', name)

          let geojson_list = []

          let geojson = {
            type: 'FeatureCollection',
            features: [
              {
                type: 'Feature',
                properties: {
                  name: name + '_' + 0,
                  time: []
                },
                geometry: {
                  coordinates: [],
                  type: 'LineString'
                }
              }
            ]
          }

          for (let d = 0; d < data.length; d++) {
            let time = date.getTime() + Math.round(Math.random() * 10000) + (d + 1) * 1000
            let current_lat = parseFloat(data[d].lat)
            let current_lon = parseFloat(data[d].lon)

            geojson['features'][0]['properties']['time'].push(time)
            geojson['features'][0]['geometry']['coordinates'].push([current_lon, current_lat])
          }

          geojson_list.push(geojson)

          // save it
          return {
            id: parseInt(data[0].id),
            name: data[0].name,
            lat: parseFloat(data[0].lat),
            lon: parseFloat(data[0].lon),
            geojson: geojson_list
          }
        })
        .catch(function(error) {
          console.log('e', error)
        })

      console.log('Parsed')
    },

    parseGeoJSON() {
      var request = new XMLHttpRequest()
      //var json;
      window.setInterval(function() {
        // make a GET request to parse the GeoJSON at the url
        request.open('GET', 'https://lordnene.github.io/MockData/GEOJSON_BRNO.json', true)
        request.onload = function() {
          if (this.status >= 200 && this.status < 400) {
            // retrieve the JSON from the response
            this.all_data = JSON.parse(this.responseText)
            console.log('in data', this.all_data)
          }
        }
        request.send()
      }, 2000)
      console.log('data', this.all_data)
      //return json;
    },

    loadGeoJSON() {
      // d3.json('https://lordnene.github.io/MockData/GEOJSON_BRNO.json', function(err, data) {
      d3.json('https://docs.mapbox.com/mapbox-gl-js/assets/hike.geojson', function(data) {
        // d3.json('https://lordnene.github.io/MockData/GEOJSON_BRNO.json', function(err, data) {
        // d3.json('https://github.com/LordNene/MockData/blob/master/GEOJSON_BRNO.json', function(err, data) {
        // d3.json('https://aqueous-spire-39478.herokuapp.com/https://github.com/LordNene/MockData/blob/master/GEOJSON_BRNO.json', function(err, data) {
        //if (err) throw err;

        console.log('in')
        console.log('dataaaaa', data)
        this.all_data = data
      })
      console.log('here')
    },

    changeData() {
      this.shown_idx = 0 //Math.floor(Math.random() * this.all_data.length);
      //this.$refs.mymap.setData(this.all_data[this.shown_idx]);
    }
  }
}
</script>

<style lang="sass" scoped>
#contents
  text-align: left
  margin-bottom: 1vh
</style>
