'use strict';
var __createBinding =
  (this && this.__createBinding) ||
  (Object.create
    ? function (o, m, k, k2) {
        if (k2 === undefined) k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (
          !desc ||
          ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)
        ) {
          desc = {
            enumerable: true,
            get: function () {
              return m[k];
            },
          };
        }
        Object.defineProperty(o, k2, desc);
      }
    : function (o, m, k, k2) {
        if (k2 === undefined) k2 = k;
        o[k2] = m[k];
      });
var __setModuleDefault =
  (this && this.__setModuleDefault) ||
  (Object.create
    ? function (o, v) {
        Object.defineProperty(o, 'default', { enumerable: true, value: v });
      }
    : function (o, v) {
        o['default'] = v;
      });
var __importStar =
  (this && this.__importStar) ||
  function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null)
      for (var k in mod)
        if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k))
          __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
  };
Object.defineProperty(exports, '__esModule', { value: true });
const path = __importStar(require('path'));
const fs = __importStar(require('fs'));
const utils_1 = require('./utils');
// считывает камеры (РАБОТАЕТ ТОЛЬКО НА ФРОНТЕНДЕ)
const getCameras = async () => {
  if (globalThis.window) {
    const devices = await window.navigator.mediaDevices.enumerateDevices();
    const cameras = devices.filter((device) => device.kind === 'videoinput');
    (0, utils_1.emit)('info', 'информация о периферии устройства получена');
    return cameras;
  } else {
    (0, utils_1.emit)('error', 'невозможно получить информацию о камерах');
    return [];
  }
};
// создаёт часть конфига с камерами
const addCamerasInConfig = async (config) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
  const cameras = (await getCameras()).map((camera) => ({
    value: camera.deviceId,
    name: camera.label,
    chosen: false,
  }));
  const camerasConfigPattern = JSON.parse(
    fs.readFileSync(path.join(__dirname, './cameraConfigPattern.json'), {
      encoding: 'utf-8',
    }),
  );
  const camerasInConfig =
    (_d =
      (_c =
        (_b = (_a = config.united) === null || _a === void 0 ? void 0 : _a.devices) ===
          null || _b === void 0
          ? void 0
          : _b.value) === null || _c === void 0
        ? void 0
        : _c.camera) === null || _d === void 0
      ? void 0
      : _d.value;
  const camerasConfig = camerasInConfig
    ? (0, utils_1.cloneObject)(camerasInConfig)
    : camerasConfigPattern;
  if (cameras.length === 0) {
    return camerasConfig;
  }
  if (
    ((_h =
      (_g =
        (_f =
          (_e =
            camerasConfig === null || camerasConfig === void 0
              ? void 0
              : camerasConfig.front_camera) === null || _e === void 0
            ? void 0
            : _e.value) === null || _f === void 0
          ? void 0
          : _f.selected_camera) === null || _g === void 0
        ? void 0
        : _g.value) === null || _h === void 0
      ? void 0
      : _h.length) === 1 &&
    ((_m =
      (_l =
        (_k =
          (_j =
            camerasConfig === null || camerasConfig === void 0
              ? void 0
              : camerasConfig.back_camera) === null || _j === void 0
            ? void 0
            : _j.value) === null || _k === void 0
          ? void 0
          : _k.selected_camera) === null || _l === void 0
        ? void 0
        : _l.value) === null || _m === void 0
      ? void 0
      : _m.length) === 1
  ) {
    cameras.unshift({ value: 'none', name: 'не выбрано', chosen: true });
    camerasConfig.front_camera.value.selected_camera.value = (0, utils_1.cloneObject)(
      cameras,
    );
    camerasConfig.back_camera.value.selected_camera.value = cameras;
  } else {
    const selectedFrontCamera =
      camerasConfig.front_camera.value.selected_camera.value.find(
        (camera) => camera.chosen,
      );
    const selectedBackCamera = camerasConfig.back_camera.value.selected_camera.value.find(
      (camera) => camera.chosen,
    );
    camerasConfig.front_camera.value.selected_camera.value = syncCameras(
      cameras,
      selectedFrontCamera,
    );
    camerasConfig.back_camera.value.selected_camera.value = syncCameras(
      cameras,
      selectedBackCamera,
    );
  }
  (0, utils_1.emit)('info', 'камеры успешно обновлены');
  return camerasConfig;
};
// сверяет старые камеры с новыми
const syncCameras = (cameras, currentCamera) => {
  const camerasCopy = (0, utils_1.cloneObject)(cameras);
  const selectedCamera = camerasCopy.find(
    (camera) =>
      camera.name === currentCamera.name || camera.value === currentCamera.value,
  );
  if (
    !selectedCamera &&
    currentCamera.value !== 'none' &&
    currentCamera.name !== 'не выбрано'
  ) {
    camerasCopy[0].chosen = false;
    currentCamera.disabled = true;
    camerasCopy.push(currentCamera);
  } else {
    if (selectedCamera) {
      camerasCopy[0].chosen = false;
      selectedCamera.chosen = true;
    }
  }
  camerasCopy.unshift({
    name: 'не выбрано',
    value: 'none',
    chosen: currentCamera.value === 'none',
  });
  return camerasCopy;
};
exports.default = addCamerasInConfig;
//# sourceMappingURL=addCamerasInConfig.js.map
