import { QUARTERS, CLASSES } from './classes.js';
import { Model } from './model.js';
import { TotalCredits } from './credits.js';


var model = new Model();


// Updates the page content to display the correct UI for the state above. If
// no quarter has been picked, then we let the user pick a quarter. Otherwise,
// we let the user pick classes within the chosen quarter.
export function ShowUI() {
  let html = []

  if (model.quarter === undefined) {
    for (let i = 0; i < QUARTERS.length; i++) {
      html.push('<div>');
      html.push(
          '<button type="button" class="btn btn-dark"' +
                 ' onclick="PickQuarter(' + i + ')">' +
          QUARTERS[i] +
          '</button>');
      html.push('</div>');
    }

  } else {
    html.push('<div><button type="button" class="btn btn-link"' +
              ' onclick="Back()">Back</button></div>');
    html.push('<p>Choose your classes:</p>');
    html.push('<div class="choices">');

    for (let i = 0; i < CLASSES[model.quarter].length; i++) {
      const name = CLASSES[model.quarter][i];
      html.push('<div class="form-check">');
      html.push('<input class="form-check-input" type="checkbox"' +
                ' value="' + i + '"' +
                (model.hasClass(name) ? ' checked' : '') +
                ' onchange="ClassChange(event)">');
      html.push('<label class="form-check-label">');
      html.push(name);
      html.push('</label>');
      html.push('</div>');
    }

    html.push('</div>');
    html.push('<p>Total of ' + TotalCredits(model.classes) + ' credits.</p>');
  }

  // Join the strings above together into one long string and insert that
  // between the start and end tags of the "content" DIV.
  let elem = document.getElementById('content');
  elem.innerHTML = html.join('\n');
}

// Called when the user clicks on a button for a particular quarter.
function PickQuarter(index) {
  model.resetQuarter(QUARTERS[index]);
  ShowUI();
}

// Called when the user clicks on the "Back" button when seeing the list of
// classes in a particular quarter.
function Back() {
  model.resetQuarter(undefined);
  ShowUI();
}

// Called when the user checks or unchecks a particular class. Updates the
// state to reflect this change.
function ClassChange(evt) {
  const cls = CLASSES[model.quarter][parseInt(evt.target.value)];
  if (evt.target.checked) {
    model.addClass(cls);
  } else {
    model.removeClass(cls);
  }
  ShowUI();
}

// Ugly fix... need these things to be global variables again.
window.PickQuarter = PickQuarter;
window.Back = Back;
window.ClassChange = ClassChange;