'use strict';

var form = document.getElementById('patient_form');
//IF THERE IS A PATIENT OBJ IN LOCAL STORAGE, THEN SHOW THE ARRAY OF OBJECTS, OTHERWISE CREATE A NEW ARRAY //
var allPatients;
if(localStorage.allPatients) {
  allPatients = JSON.parse(localStorage.allPatients);
} else {
  allPatients = [];
}

function Patient(name, date, exercise, comments) {
  this.patientName = name;
  this.entry = [];
  this.entry.push({
    date: date,
    exercise: exercise,
    comments: comments
  });
}

function formData(event) {
  var currentPatients = 0;
  var name = event.target.name.value;
  var date = event.target.date.value;
  var exercise = event.target.exercise.value;
  var comments = event.target.comments.value;
  for (var i = 0; i < allPatients.length; i++) {
    if (name.toLowerCase() === allPatients[i].patientName.toLowerCase()) {
      allPatients[i].entry.push({
        date: date,
        exercise: exercise,
        comments: comments
      });
    } else {
      currentPatients++;
    }
  }
  if (currentPatients === allPatients.length) {
    allPatients.push(new Patient(name, date, exercise, comments));
  }
  localStorage.allPatients = JSON.stringify(allPatients);
  event.preventDefault();
  form.reset();
}

form.addEventListener('submit', formData);

function videoLoader() {
  if (localStorage.youtubeURL) {
    document.getElementById('local').setAttribute('src', localStorage.youtubeURL);
  }
}
window.onload = videoLoader();
