var __asyncValues = (this && this.__asyncValues) || function (o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
import { Component, h, Host, State } from '@stencil/core';
import { pipe } from 'fp-ts/function';
import * as O from 'fp-ts/Option';
import { getOrDefault, getOrError } from '../../../utils';
import carsCalculatorApi from '../api/cars-calculator.api';
import eventTrackingService from '../services/event-tracking.service';
import sessionQuery from '../services/session.query';
import sessionStore from '../services/session.store';
export class ChooseVehicleSection {
  constructor() {
    this.toCapitalCase = (str) => str === null || str === void 0 ? void 0 : str.split(' ').map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join(' ');
    sessionQuery.vehicle$.subscribe((state) => (this.vehicleInfo = state));
    sessionQuery.makeList$.subscribe((state) => (this.makeList = getOrDefault(state, [])));
    sessionQuery.modelList$.subscribe((state) => (this.modelList = getOrDefault(state, [])));
    sessionQuery.yearList$.subscribe((state) => (this.yearList = getOrDefault(state, [])));
    sessionQuery.bodyTypeList$.subscribe((state) => (this.bodyTypeList = getOrDefault(state, [])));
  }
  render() {
    return (h(Host, null,
      h("div", { class: "d-flex flex-column flex-wrap flex-md-row align-items-center justify-content-center h4" },
        h("div", { class: "d-flex align-items-center" }, "Calculate my savings on a"),
        h("div", { class: "d-flex mx-2 my-2 my-md-0" },
          h("div", { class: "btn-group", role: "group", "aria-label": "New or used vehicle" },
            h("button", { type: "button", class: {
                'btn btn-outline-dark px-5': true,
                active: !this.isUsedCarSelected()
              }, onClick: (_event) => {
                sessionStore.setVehicleState('isUsedCarRequested', false);
                eventTrackingService.trackInputChangedAsync({
                  key: 'isUsedCar',
                  value: 'false'
                });
              } }, "New"),
            h("button", { type: "button", class: {
                'btn btn-outline-dark px-5': true,
                active: this.isUsedCarSelected()
              }, onClick: (_event) => {
                sessionStore.setVehicleState('isUsedCarRequested', true);
                eventTrackingService.trackInputChangedAsync({
                  key: 'isUsedCar',
                  value: 'true'
                });
              } }, "Used"))),
        this.isUsedCarSelected() ? (h("div", { class: "d-flex flex-column flex-md-row align-items-center justify-content-center my-0 my-md-2 my-xl-0" },
          h("span", { class: "pr-0 pr-sm-2 d-flex text-center" }, "vehicle, with a purchase price of"),
          h("input", { placeholder: "25000", type: "text", class: "form-control d-flex w-auto mt-2 mt-md-0", value: '$' + this.getVehicleInfo('approximatePrice'), onInput: (e) => {
              const el = e.target;
              el.value = el.value.replace(/\D/g, '');
            }, onFocus: (e) => {
              const el = e.target;
              el.value = el.value.replace('$', '');
            }, onBlur: (e) => {
              const el = e.target;
              el.value = '$' + el.value;
            }, onChange: (e) => {
              const elmValue = e.target.value;
              const newValue = (elmValue === null || elmValue === void 0 ? void 0 : elmValue.length) > 0 ? parseFloat(elmValue) : null;
              sessionStore.setVehicleState('approximatePrice', newValue);
              eventTrackingService.trackInputChangedAsync({
                key: 'approximatePrice',
                value: String(newValue)
              });
            } }))) : (h("div", { class: "d-flex align-items-center" }, "vehicle"))),
      h("div", { class: "d-flex flex-wrap flex-column flex-md-row align-items-center justify-content-center mt-5 h4" },
        h("div", { class: "d-flex align-items-center" }, "I'm interested in a"),
        h("div", { class: "d-flex mx-2 my-2 my-md-0" },
          h("fl-dropdown", { options: this.makeList, requiredValidationMessage: "Select an option", placeholder: "select make", value: this.getVehicleInfo('makeId'), onValueChanged: (e) => this.chooseMake(e.detail.label, e.detail.value) })),
        h("div", { class: "d-flex mx-2 my-2 my-md-0" },
          h("fl-dropdown", { options: this.modelList, requiredValidationMessage: "Select an option", placeholder: "select model", value: this.getVehicleInfo('modelId'), disabled: O.isNone(this.vehicleInfo.makeId), onValueChanged: (e) => this.chooseModel(e.detail.label, e.detail.value) })),
        h("div", { class: "d-flex mx-2 my-2 my-xl-0" },
          h("fl-dropdown", { options: this.yearList, requiredValidationMessage: "Select an option", placeholder: "select year", value: this.getVehicleInfo('year'), disabled: O.isNone(this.vehicleInfo.modelId), onValueChanged: (e) => this.chooseYear(e.detail.value) }))),
      h("div", { class: "d-flex align-items-center justify-content-center justify-content-md-start mt-5" },
        h("div", { class: "btn-group flex-wrap", role: "group", "aria-label": "Body types" }, this.bodyTypeList.map((bodyType) => (h("button", { type: "button", class: {
            'btn btn-sm btn-outline-dark px-5': true,
            active: this.isBodyTypeSelected(bodyType.value)
          }, onClick: (_event) => this.chooseBodyType(bodyType.label, bodyType.value) }, bodyType.label)))))));
  }
  async componentDidLoad() {
    var _a;
    if (((_a = this.makeList) === null || _a === void 0 ? void 0 : _a.length) > 0)
      return;
    const carsMakes = await carsCalculatorApi.getCarsMakes();
    sessionStore.updateList('makeList', carsMakes.map((make) => ({
      label: this.toCapitalCase(make.name),
      value: make.make_id
    })));
    eventTrackingService.trackStepProgressedAsync({ stepName: 'carSelection' });
  }
  async chooseMake(make, makeId) {
    var _a;
    this.clearModelStates();
    this.clearYearStates();
    this.clearBodyTypeStates();
    this.clearVariantsList();
    if (((_a = this.modelList) === null || _a === void 0 ? void 0 : _a.length) === 0) {
      sessionStore.updateList('modelList', (await carsCalculatorApi.getCarsModels(makeId)).map((model) => ({
        label: this.toCapitalCase(model.model_code),
        value: model.model_id
      })));
    }
    sessionStore.setVehicleState('make', make);
    sessionStore.setVehicleState('makeId', makeId);
    eventTrackingService.trackInputChangedAsync({
      key: 'make',
      value: make
    });
  }
  async chooseModel(model, modelId) {
    var _a;
    this.clearYearStates();
    this.clearBodyTypeStates();
    this.clearVariantsList();
    if (((_a = this.yearList) === null || _a === void 0 ? void 0 : _a.length) === 0) {
      sessionStore.updateList('yearList', (await carsCalculatorApi.getCarsModelYears(modelId))
        .sort()
        .reverse()
        .map((year) => ({
        label: year.toString(),
        value: year
      })));
    }
    sessionStore.setVehicleState('model', model);
    sessionStore.setVehicleState('modelId', modelId);
    eventTrackingService.trackInputChangedAsync({
      key: 'model',
      value: model
    });
  }
  async chooseYear(year) {
    var _a;
    this.clearBodyTypeStates();
    this.clearVariantsList();
    const modelId = getOrError(this.vehicleInfo.modelId);
    if (((_a = this.bodyTypeList) === null || _a === void 0 ? void 0 : _a.length) === 0) {
      sessionStore.updateList('bodyTypeList', (await carsCalculatorApi.getCarsModelBodyTypes(modelId, year)).map((bodyType) => ({
        label: bodyType.body_type,
        value: bodyType.body_type_id
      })));
    }
    sessionStore.setVehicleState('year', year);
    this.chooseBodyType(this.bodyTypeList[0].label, this.bodyTypeList[0].value);
    eventTrackingService.trackInputChangedAsync({
      key: 'year',
      value: year.toString()
    });
  }
  async chooseBodyType(bodyType, bodyTypeId) {
    var e_1, _a;
    this.clearVariantsList();
    sessionStore.setVehicleState('bodyType', bodyType);
    sessionStore.setVehicleState('bodyTypeId', bodyTypeId);
    const modelId = getOrError(this.vehicleInfo.modelId);
    const year = getOrError(this.vehicleInfo.year);
    const variantPromises = (await carsCalculatorApi.getCarsModelVariant(modelId, year, bodyTypeId)).map(async (variant) => {
      var _a;
      const photoUri = await carsCalculatorApi.getCarsVariantPhotos(variant.variant_id);
      return {
        variantId: variant.variant_id,
        description: variant.short_description,
        buildYear: variant.build_year,
        modelMonth: variant.model_month,
        listPriceGross: variant.list_price_gross,
        engineLitres: variant.engine_litres,
        transmission: variant.transmission,
        fuelTypeId: variant.fuel_type_translation_id,
        photoUri: O.fromNullable((_a = photoUri === null || photoUri === void 0 ? void 0 : photoUri[0]) === null || _a === void 0 ? void 0 : _a.photo_uri)
      };
    });
    const variantList = [];
    try {
      for (var variantPromises_1 = __asyncValues(variantPromises), variantPromises_1_1; variantPromises_1_1 = await variantPromises_1.next(), !variantPromises_1_1.done;) {
        const variant = variantPromises_1_1.value;
        variantList.push(variant);
      }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
      try {
        if (variantPromises_1_1 && !variantPromises_1_1.done && (_a = variantPromises_1.return)) await _a.call(variantPromises_1);
      }
      finally { if (e_1) throw e_1.error; }
    }
    sessionStore.updateList('modelVariantsList', variantList);
    eventTrackingService.trackStepProgressedAsync({ stepName: 'variantSelection' });
    eventTrackingService.trackInputChangedAsync({
      key: 'bodyType',
      value: bodyType
    });
  }
  clearModelStates() {
    this.modelList = [];
    this.clearVehicleState('model');
    this.clearVehicleState('modelId');
  }
  clearYearStates() {
    this.yearList = [];
    this.clearVehicleState('year');
  }
  clearBodyTypeStates() {
    this.bodyTypeList = [];
    this.clearVehicleState('bodyType');
    this.clearVehicleState('bodyTypeId');
  }
  clearVariantsList() {
    sessionStore.updateList('modelVariantsList', []);
  }
  clearVehicleState(key) {
    sessionStore.setVehicleState(key, null);
  }
  getVehicleInfo(key) {
    return pipe(this.vehicleInfo[key], O.getOrElse(() => ''));
  }
  isBodyTypeSelected(bodyTypeId) {
    return pipe(this.vehicleInfo.bodyTypeId, O.fold(() => false, (selectedBodyTypeId) => selectedBodyTypeId === bodyTypeId));
  }
  isUsedCarSelected() {
    return pipe(this.vehicleInfo.isUsedCarRequested, O.getOrElse(() => false));
  }
  static get is() { return "ap-ben-choose-vehicle-section"; }
  static get states() { return {
    "makeList": {},
    "modelList": {},
    "yearList": {},
    "bodyTypeList": {},
    "vehicleInfo": {}
  }; }
}
