import { JSDOM } from 'jsdom';
import Car from '../model/Car';
import Selectors from '../util/Selectors';

class Scraper {
  document;
  car;

  setContent(text) {
    const parsedContent = new JSDOM(text).window.document;
    if (parsedContent.querySelector(Selectors.properties.main.container) === null) {
      throw Error('No data was received.. Something went wrong.');
    }
    this.document = parsedContent;
  }

  getTextBySelector(selector) {
    return this.document.querySelector(selector).innerHTML;
  }

  scrapeMainProperties() {
    const {
      main: selector,
    } = Selectors.properties;
    this.document
      .querySelector(selector.container)
      .querySelectorAll(selector.rows)
      .forEach((field) => {
        const value = field.querySelectorAll(selector.cell);
        let data;
        if (value[1].childElementCount > 0) {
          data = value[1].querySelector(selector.irregularText).innerHTML;
        } else {
          data = value[1].innerHTML;
        }
        let key = value[0].innerHTML;
        if (key.charAt(key.length - 1) === ':') {
          key = key.substring(0, key.length - 1).toLowerCase();
        }
        this.car[key] = data;
      });
  }

  scrapeBasicProperties() {
    if (!this.document) {
      throw Error('No data to scrape.');
    }
    const {
      properties: selector,
    } = Selectors;
    const plate = this.getTextBySelector(selector.plate);
    const carName = this.getTextBySelector(selector.name);
    const vin = this.getTextBySelector(selector.vin);
    this.car = new Car(plate, carName, vin.substring(5));
    return this.car;
  }
}

export default Scraper;
