/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
  __markAsModule(target);
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, desc) => {
  if (module2 && typeof module2 === "object" || typeof module2 === "function") {
    for (let key of __getOwnPropNames(module2))
      if (!__hasOwnProp.call(target, key) && key !== "default")
        __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
  }
  return target;
};
var __toModule = (module2) => {
  return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};

// main.ts
__export(exports, {
  default: () => main_default
});

// src/App.ts
var import_obsidian3 = __toModule(require("obsidian"));

// src/Modal.ts
var import_obsidian = __toModule(require("obsidian"));
var CameraModal = class extends import_obsidian.Modal {
  constructor(app2, cameraSettings) {
    super(app2);
    this.videoStream = null;
    this.chosenFolderPath = cameraSettings.chosenFolderPath;
  }
  onOpen() {
    return __async(this, null, function* () {
      const { contentEl } = this;
      const webCamContainer = contentEl.createDiv();
      const statusMsg = webCamContainer.createEl("span", { text: "Loading.." });
      const videoEl = webCamContainer.createEl("video");
      const buttonsDiv = webCamContainer.createDiv();
      const firstRow = buttonsDiv.createDiv();
      const secondRow = buttonsDiv.createDiv();
      const recordVideoButton = firstRow.createEl("button", {
        text: "Start recording"
      });
      const switchCameraButton = firstRow.createEl("button", {
        text: "Switch Camera"
      });
      const snapPhotoButton = firstRow.createEl("button", {
        text: "Take a snap"
      });
      firstRow.style.display = "none";
      secondRow.style.display = "none";
      const filePicker = secondRow.createEl("input", {
        placeholder: "Choose image file from system",
        type: "file"
      });
      filePicker.accept = "image/*,video/*";
      filePicker.capture = "camera";
      const filePicker2 = secondRow.createEl("input", {
        placeholder: "Choose image file from system",
        type: "file"
      });
      filePicker2.accept = "image/*";
      filePicker2.capture = "camera";
      videoEl.autoplay = true;
      videoEl.muted = true;
      const chunks = [];
      let recorder = null;
      this.videoStream = null;
      const cameras = (yield navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "videoinput");
      if (cameras.length <= 1)
        switchCameraButton.style.display = "none";
      let cameraIndex = 0;
      const getVideoStream = () => __async(this, null, function* () {
        try {
          return yield navigator.mediaDevices.getUserMedia({
            video: { deviceId: cameras[cameraIndex].deviceId },
            audio: true
          });
        } catch (error) {
          console.log(error);
          return null;
        }
      });
      this.videoStream = yield getVideoStream();
      if (this.videoStream) {
        firstRow.style.display = "block";
        secondRow.style.display = "block";
        statusMsg.style.display = "none";
      } else {
        secondRow.style.display = "block";
        statusMsg.textContent = "Error in loading videostream in your device..";
      }
      const handleImageSelectChange = (file) => __async(this, null, function* () {
        const chosenFile = file;
        const bufferFile = yield chosenFile.arrayBuffer();
        saveFile(bufferFile, false, chosenFile.name.split(" ").join("-"));
      });
      filePicker.onchange = () => handleImageSelectChange(filePicker.files[0]);
      filePicker2.onchange = () => handleImageSelectChange(filePicker2.files[0]);
      const view = this.app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
      const saveFile = (file, isImage = false, fileName = "") => __async(this, null, function* () {
        if (!fileName) {
          const dateString = (new Date() + "").slice(4, 28).split(" ").join("_").split(":").join("-");
          fileName = isImage ? `image_${dateString}.png` : `video_${dateString}.webm`;
        }
        if (!isImage)
          new import_obsidian.Notice("Adding video to vault...");
        const filePath = this.chosenFolderPath + "/" + fileName;
        const folderExists = app.vault.getAbstractFileByPath(this.chosenFolderPath);
        if (!folderExists)
          yield app.vault.createFolder(this.chosenFolderPath);
        const fileExists = app.vault.getAbstractFileByPath(filePath);
        if (!fileExists)
          yield app.vault.createBinary(filePath, file);
        if (!view)
          return new import_obsidian.Notice(`Saved to ${filePath}`);
        const cursor = view.editor.getCursor();
        view.editor.replaceRange(isImage ? `![${fileName}](${filePath})
` : `
![[${filePath}]]
`, cursor);
        this.close();
      });
      switchCameraButton.onclick = () => __async(this, null, function* () {
        cameraIndex = (cameraIndex + 1) % cameras.length;
        this.videoStream = yield getVideoStream();
      });
      snapPhotoButton.onclick = () => {
        const canvas = webCamContainer.createEl("canvas");
        canvas.style.display = "none";
        const { videoHeight, videoWidth } = videoEl;
        canvas.height = videoHeight;
        canvas.width = videoWidth;
        canvas.getContext("2d").drawImage(videoEl, 0, 0, videoWidth, videoHeight);
        canvas.toBlob((blob) => __async(this, null, function* () {
          const bufferFile = yield blob.arrayBuffer();
          saveFile(bufferFile, true);
        }), "image/png");
      };
      videoEl.srcObject = this.videoStream;
      recordVideoButton.onclick = () => __async(this, null, function* () {
        switchCameraButton.disabled = true;
        let isRecording = recorder && recorder.state === "recording";
        if (isRecording)
          recorder.stop();
        isRecording = !isRecording;
        recordVideoButton.innerText = isRecording ? "Stop Recording" : "Start Recording";
        if (!recorder) {
          recorder = new MediaRecorder(this.videoStream, {
            mimeType: "video/webm"
          });
        }
        recorder.ondataavailable = (e) => chunks.push(e.data);
        recorder.onstop = (_) => __async(this, null, function* () {
          const blob = new Blob(chunks, {
            type: "audio/ogg; codecs=opus"
          });
          const bufferFile = yield blob.arrayBuffer();
          saveFile(bufferFile, false);
        });
        recorder.start();
      });
    });
  }
  onClose() {
    var _a;
    const { contentEl } = this;
    (_a = this.videoStream) == null ? void 0 : _a.getTracks().forEach((track) => {
      track.stop();
    });
    contentEl.empty();
  }
};
var Modal_default = CameraModal;

// src/SettingsTab.ts
var import_obsidian2 = __toModule(require("obsidian"));
var DEFAULT_SETTINGS = {
  chosenFolderPath: "attachments/snaps"
};
var CameraSettingsTab = class extends import_obsidian2.PluginSettingTab {
  constructor(app2, plugin) {
    super(app2, plugin);
    this.plugin = plugin;
  }
  display() {
    const { containerEl } = this;
    containerEl.empty();
    containerEl.createEl("h2", { text: "Obsidian-Camera settings" });
    new import_obsidian2.Setting(containerEl).setName("Folder Path").setDesc("Folder where the videos and snaps should be saved").addText((text) => text.setPlaceholder("Enter your secret").setValue(this.plugin.settings.chosenFolderPath).onChange((value) => __async(this, null, function* () {
      console.log("Chosen Folder Path: " + value);
      this.plugin.settings.chosenFolderPath = value;
      yield this.plugin.saveSettings();
    })));
  }
};

// src/App.ts
var ObsidianCamera = class extends import_obsidian3.Plugin {
  onload() {
    return __async(this, null, function* () {
      yield this.loadSettings();
      this.addRibbonIcon("camera", "Obsidian Camera", (evt) => {
        new Modal_default(this.app, this.settings).open();
      });
      this.addSettingTab(new CameraSettingsTab(this.app, this));
      this.addCommand({
        id: "Open camera modal",
        name: "Open camera modal / File Picker",
        callback: () => {
          new Modal_default(this.app, this.settings).open();
        }
      });
    });
  }
  loadSettings() {
    return __async(this, null, function* () {
      this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData());
    });
  }
  saveSettings() {
    return __async(this, null, function* () {
      yield this.saveData(this.settings);
    });
  }
};

// main.ts
var main_default = ObsidianCamera;
//# sourceMappingURL=data:application/json;base64,[encoded data, 16516 characters]
