'use strict';

// TODO is there a better way?
const symbolScanner = {
  // Our list of Moto scanners that we can look up
  manufacturer: 'Symbol / Motorola',
  models: [
    // 'MC3190',
    // 'MC32N0',
    'MC9000',
    'MC9060',
    'MC9090',
    // 'MC9190',
    // 'MC92N0',
  ],
};

const psionScanner = {
  // TODO Implement Psion WAP configurations
  manufacturer: 'Psion Techlogix',
  models: ['WAP4'],
};

const mc9000 = {
  // This should handle 9000/9060/9090 series
  config: 'MC',
  productFamily: '90',
  radio: ['0', '6', '9'],
  wan: ['0', '2', '3', '4', '7'],
  formFactor: ['G', 'K', 'S'],
  scanEngine: ['F', 'H', 'J', 'K', 'U', 'W'],
  carrier: ['0', 'A', 'B', 'E', 'F'],
  display: ['H', 'J'],
  memory: ['A', 'B', 'C', 'J', '9'],
  keyboard: ['A', 'E', 'F', 'G', 'H', 'J', 'L'],
  operatingSystem: ['B', 'E', 'F', 'G', 'H', 'Q'],
  features: ['00', 'A2', 'A4', 'A6', 'A7', 'B5', 'B6', 'C2', 'C6'],
  region: ['00', '50', 'US', 'FB', 'WW', 'WR'],
  // NOTE These won't work for multiple devices...
  productPage: 'http://insert.the.url',
  productManual: 'manual.pdf',
  // Maybe we can use a multi-dimensional array..
  productInfo: [
    ['MC9000', 'http://url', 'manual.pdf'],
    ['MC9060', 'http://url', 'manual.pdf'],
    ['MC9090', 'http://url', 'manual.pdf'],
  ],

  // TODO Parse function in each object?

  // TODO Reference each config variable to a description

  // TODO Error Checking (make sure an entered value exists in our table above)
};

// SELECTORS
const devices = document.querySelector('.devices');
const btnSubmit = document.querySelector('.btnSubmit');
const btnSubmitStr = document.querySelector('.btnSubmitStr');
const btnReset = document.querySelector('.btnReset');
const btnClear = document.querySelector('.btnClear');
const strConfig = document.getElementById('configuration-string');
const results = document.querySelector('.results');

// Initialize defaults
const init = function () {
  // TODO Load last selected device and input fields from localStorage in case of browser crash...
  let bSelected = false;
  let arr = symbolScanner.models.sort();

  for (let i = 0; i < symbolScanner.models.length; i++) {
    let opt = arr[i];
    var el = document.createElement('option');
    el.textContent = opt; // The text that shows up in the dropdown
    el.value = opt; // We can set the value here, if we want to change it...

    if (opt === 'MC9090') el.setAttribute('selected', bSelected); // Set the default option to 9090

    devices.appendChild(el);
  }
};

window.onload = init; // Initialize on page load...

// FIXME Here's the heart of the application. We'll parse the given string, check for errors, and use this to lookup specific values. Multiple returns aren't great here
const parseConfiguration = function (model, config) {
  const [c1, c2, fam1, fam2, radio, wan] = model.split('');
  const [
    formFactor,
    scanEngine,
    carrier,
    display,
    memory,
    keyboard,
    operatingSystem,
    f1,
    f2,
    r1,
    r2,
  ] = config.toUpperCase().split(''); // Make sure everything is uppercase

  // Combine multi-digit values
  const config_ = c1 + c2;
  const family = fam1 + fam2;
  const features = f1 + f2;
  const region = r1 + r2;

  // Debugging text, so I can view the config string
  console.log(`${model}-${config.toUpperCase()}`);
  console.log(
    config_,
    family,
    radio,
    wan,
    scanEngine,
    display,
    memory,
    keyboard,
    operatingSystem,
    features,
    region
  );

  return [
    config_,
    family,
    radio,
    wan,
    formFactor,
    scanEngine,
    carrier,
    display,
    memory,
    keyboard,
    operatingSystem,
    features,
    region,
  ];
};
// parseConfiguration('MC9090', 'GJ0HJHGA6WR'); // IT WORKS!

btnSubmit.addEventListener('click', function () {
  // Submit button
  console.log('Submit button');
});

btnSubmitStr.addEventListener('click', function () {
  // Submit button (config string)
  // NOTE This was for testing the parser. Might move to individual functions inside the scanner objects

  // Check to make sure our string is the correct length
  // TODO Each device will have a different check
  if (strConfig.value.length !== 11) {
    alert('Please enter a valid configuration string!');
    return;
  }

  const result = parseConfiguration(devices.value, strConfig.value);
  console.log(result);

  if (
    devices.value === 'MC9000' ||
    devices.value === 'MC9060' ||
    devices.value === 'MC9090'
  ) {
    // use mc9000 object
    console.log('Is an MC9000 Series device');
    for (let i = 0; i < result.length; i++) {
      // for (let j = 0; j < mc9000.display.length; j++) {
      //   if (result[7] === mc9000.display[j]) {
      //     // FIXME It's finding the result, but it's finding it with EACH iteration of the result loop
      //     console.log(i, j, 'Found it!');
      //   }
      // }
      if (mc9000.display.includes(result[i]))
        console.log('Found', mc9000.display, result[i], i);
    }
  }

  results.classList.remove('hidden'); // show the results table
});

btnReset.addEventListener('click', function () {
  // Reset select boxes
  console.log('Reset Button');
});

btnClear.addEventListener('click', function () {
  // Clear input string
  console.log('Clear button');
  strConfig.value = ''; // Clear the input field
  results.classList.add('hidden'); // Hide the results table
});

devices.addEventListener('change', function () {
  //  Check image exists or display default image
  fetch(`images/${devices.value}.png`, { method: 'HEAD' })
    .then(res => {
      if (res.ok) {
        document.getElementById(
          'device-image'
        ).src = `images/${devices.value}.png`;
        document.getElementById(
          'device-image'
        ).alt = `Image of ${devices.value} scanner`;
      } else {
        document.getElementById('device-image').src = 'images/blank.png';
        document.getElementById('device-image').alt = 'No Image';
      }
    })
    .catch(err => console.error('Error:', err));

  // TODO also populate the individual selectors :D

  // TODO Insert links to product page and user manual
});

// Testing
// function generateTableHead(table, data) {
//   let thead = table.createTHead();
//   let row = thead.insertRow();

//   for (let key of data) {
//     let th = document.createElement('th');
//     let text = document.createTextNode(key);
//     th.appendChild(text);
//     row.appendChild(th);
//   }
// }

// function generateTable(table, data) {
//   for (let element of data) {
//     let row = table.insertRow();
//     for (key in element) {
//       let cell = row.insertCell();
//       let text = document.createTextNode(element[key]);
//       cell.appendChild(text);
//     }
//   }
// }

// let table = document.querySelector('table');
// generateTableHead(table, ['Parameter', 'Code', 'Result']);
// generateTable(table, ['Scan Engine', 'J', 'Lorax Scan Engine']);
