<template>
  <div class="home">

    <button @click="StartButtonPressed">Start</button>
  </div>
</template>

<script>

export default {
  name: 'HomeView',
  data(){
    return{
      // This object holds all state of the app
      classes: [
        ['h1', 'Heading 1', '6rem', '300', '-.015625em', -1],
        ['h2', 'Heading 2', '3.75rem', '300', '-.0083333333em', 0],
        ['h3', 'Heading 3', '3rem', '400', 'normal', 1],
        ['h4', 'Heading 4', '2.125rem', '400', '.0073529412em', 2],
        ['h5', 'Heading 5', '1.5rem', '400', 'normal', 2],
        ['h6', 'Heading 6', '1.25rem', '500', '.0125em', 3],
        ['subtitle-1', 'Subtitle 1', '1rem', '400', '.009375em', 4],
        ['subtitle-2', 'Subtitle 2', '0.875rem', '500', '.0071428571em', 4],
        ['body-1', 'Body 1', '1rem', '400', '.03125em', 4],
        ['body-2', 'Body 2', '0.875rem', '400', '.0178571429em', 4],
        ['button', 'Button', '0.875rem', '500', '.0892857143em', 4],
        ['caption', 'Caption', '0.75rem', '400', '.0333333333em', 4],
        ['overline', 'Overline', '0.75rem', '500', '.1666666667em', 4],
      ],
      //meineReaktiveVariable: "Leon",
      AlteSeite: 0,
      NeueSeite: 0,

      pdf: 0,
      valid:true,
      Vorname:"",
      Nachname:"",
      nameRules:  [
        v => !!v || 'Feld muss ausgefüllt sein',
      ],
      Anrede:"",
      Mail:"",
      emailRules: [
        v => !!v || 'Feld muss ausgefüllt sein',
        v => /.+@.+\..+/.test(v) || 'Eingabe ungültig',
      ],
      Firma:"",
      Raum:"",
      Zusatzinfos:"",

      date:{},
      time:{},

      Timeframe: 250,
      UpperPercentile: 0.9,
      LowerPercentile: 0.1,
      LimitA: 2.5,
      LimitB:10.0,

      audioCtx:{},
      source:{},
      stream:{},
      Gain:{},
      HPF:{},
      LPF:{},
      analyser:{},
      LevelAnalyser:{},
      LevelBuffer:{},

      AnimationID:{},
      id:{},

      bufferLength:{},
      dataArray:{},
      RecentRMS: 0,
      ByteToDecimal: 0,
      RecentLevelValue: 0,

      ArrayCounter:0,
      LevelValues:[],
      CummulatedLevelValues:0,
      SortedArray:[],
      IndexMax:{},
      IndexMin:{},
      PercentileValue:{},

      height:0,
      value:1,
      secondsDown:25,

      Result:{},
      ResultABC:{},

      MicError:0,
      bandPass1:{},


    }

  },
  methods: {
    // Write your own functions that mutate data via `this.`
    nextPage() {
      // this.seite = (this.seite + 1) % 3;
      this.AlteSeite = this.NeueSeite
      this.NeueSeite = (this.NeueSeite + 1);
    },
    firstPage() {
      this.AlteSeite = this.NeueSeite;
      this.NeueSeite = 0;
    },
    previousPage() {
      this.NeueSeite = this.AlteSeite;
      this.AlteSeite = (this.AlteSeite - 1);
      this.pdf = 0;
    },

    pdfForm() {
      this.pdf = 1;
    },


    about() {
      this.AlteSeite = this.NeueSeite;
      this.NeueSeite = 10;
    },





    ResetLevelValues() {
      this.ArrayCounter = 0;
      this.LevelValues = [];
    },


    RMStoDBFS(InputArray){
      for (var i = 0; i < InputArray.length; i++) {
        InputArray[i] = 20 * Math.log10(InputArray[i])
      }
    },

    numSort(a, b) {
      return (a - b);
    },


    Percentile(InputArray) {

      this.SortedArray = InputArray.sort(this.numSort);
      this.RMStoDBFS(this.SortedArray);
      //console.log('Sortiertes Array DBFS: ' + SortedArray);

      this.IndexMax = Math.round(this.SortedArray.length * this.UpperPercentile);
      this.IndexMin = Math.round(this.SortedArray.length * this.LowerPercentile);
      this.PercentileValue = this.SortedArray[this.IndexMax] - this.SortedArray[this.IndexMin];
      this.PercentileValue = this.PercentileValue.toFixed(2); //nach zwei Dazimalstellen abbrechen
      console.log('percentile Value = ' + this.PercentileValue);

      if (this.PercentileValue < this.LimitA) {
        this.Result = 1
        this.ResultABC = "A"
      } else if (this.PercentileValue < this.LimitB) {
        this.Result = 2
        this.ResultABC = "B"
      }
      else {
        this.Result = 3
        this.ResultABC = "C"
      }
      //console.log('seite = ' + this.seite);

      this.NeueSeite = 4;
      this.ResetLevelValues();
    },


    stopmeasurement() {
      window.cancelAnimationFrame(this.AnimationID);
      clearInterval(this.id);
      console.log('Measurement stopped.');
      this.height = 0;
      this.secondsDown = 25;
      this.CummulatedLevelValues = 0;
    },

    frame() {
      if (this.height == 100) {
        this.stopmeasurement();
        this.Percentile(this.LevelValues);


        console.log("OK");
      }
      else {
        this.height++;
        console.log(this.height);
        this.value = this.height+2;
        console.log(this.height);
        if (this.height % 4 == 0){
          this.secondsDown = 25 - (this.height/4);
        }
      }
    },

    startmeasurement() {
      //this.visualize();
      this.ResetLevelValues();

      var today = new Date();
      this.date = today.getDate()+'.'+(today.getMonth()+1)+'.'+today.getFullYear();
      this.time = today.getHours()+':'+today.getMinutes();
      //requestAnimationFrame(this.RecentLevel);
      this.height = 0;
      requestAnimationFrame(this.RecentLevel);
      this.id = setInterval(this.frame, this.Timeframe);
      //this.frame();

    },

    CancleMeasurement() {
      this.stopmeasurement();
      this.previousPage();
      this.MicError=0;
    },

    //RMS Value
    RecentLevel(){
      this.LevelAnalyser.getByteTimeDomainData(this.LevelBuffer);

      for (var i = 0; i < 512; i++) {
        this.ByteToDecimal = (this.LevelBuffer[i]-128)/128;
        //console.log("LevelBuffer i = "+ self.LevelBuffer[i]);
        this.RecentRMS += this.ByteToDecimal * this.ByteToDecimal;
      }
      this.RecentRMS /= 512;
      this.RecentLevelValue = Math.sqrt(this.RecentRMS);

      this.LevelValues[this.ArrayCounter] = this.RecentLevelValue;

      this.CummulatedLevelValues = this.CummulatedLevelValues + this.RecentLevelValue*1000;
      if (this.ArrayCounter > 200 && this.CummulatedLevelValues < 50){
        this.stopmeasurement();
        this.MicError = 1;
      }

      if (isNaN(this.RecentLevelValue)){
        this.stopmeasurement();
        this.MicError = 1;
      }

      if (this.RecentLevelValue > 0.5){
        this.stopmeasurement();
        this.MicError = 2;
      }
      ++this.ArrayCounter;
      console.log("Recent Level",this.RecentLevelValue);
      this.AnimationID = requestAnimationFrame(this.RecentLevel);
    },




    StartButtonPressed(){

      let constraints = {
        audio : {
          autoGainControl : false,
          echoCancellation : false,
          noiseSuppression : false
        }
      }
      if (navigator.mediaDevices.getUserMedia) {
        console.log('getUserMedia supported.');
        navigator.mediaDevices.getUserMedia(constraints).then((stream)=> {

          this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();

          //set up the different audio nodes we will use for the app

          this.Gain = this.audioCtx.createGain();
          this.Gain.gain.setValueAtTime(2.0, this.audioCtx.currentTime);
          // this.Gain.gain.setValueAtTime(0.5,0);

          this.HPF = this.audioCtx.createBiquadFilter();
          this.HPF.type = "highpass";
          this.HPF.frequency.value = 450;

          this.LPF = this.audioCtx.createBiquadFilter();
          this.LPF.type = "lowpass";
          this.LPF.frequency.value = 10000;

          this.bandPass1=this.audioCtx.createBiquadFilter();
          this.bandPass1.type='bandpass'
          this.bandPass1.frequency.value=63;
          this.bandPass1.Q.value=1.41;



          this.analyser = this.audioCtx.createAnalyser();
          this.analyser.fftSize = 256;
          this.analyser.minDecibels = -90;
          this.analyser.maxDecibels = -10;
          this.analyser.smoothingTimeConstant = 0.9;

          this.LevelAnalyser = this.audioCtx.createAnalyser();
          this.LevelAnalyser.fftSize = 512;
          this.LevelAnalyser.minDecibels = -100;
          this.LevelAnalyser.maxDecibels = -1;
          this.LevelAnalyser.smoothingTimeConstant = 0.95;
          this.LevelBuffer = new Uint8Array(512);

          this.source = this.audioCtx.createMediaStreamSource(stream);
          this.source.connect(this.Gain);
          this.Gain.connect(this.HPF);
          this.HPF.connect(this.LPF);
          this.LPF.connect(this.analyser);
          this.LPF.connect(this.LevelAnalyser);
          this.bandPass1.connect(this.LPF);

          this.bandPass1.connect(this.audioCtx.destination);
          // this.LevelAnalyser.connect(this.audioCtx.destination);

          this.FirstStart = false;
          //this.startmeasurement();
          setTimeout(this.startmeasurement, 800); //short break to avoid zeros at beginning of measurement
        })

            // Error callback
            .catch(function(err) {
              console.log('The following gUM error occured: ' + err);
            })
      }
      else {
        console.log('Error: This Site is not supported on your browser!');
      }

    }
  },
}
</script>
