/*
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: () => ObsidianCamera
});
var import_obsidian = __toModule(require("obsidian"));
var ObsidianCamera = class extends import_obsidian.Plugin {
  onload() {
    return __async(this, null, function* () {
      this.addRibbonIcon("camera", "Obsidian Camera", (evt) => {
        new CameraModal(this.app).open();
      });
      this.addCommand({
        id: "Open camera modal",
        name: "Open camera modal / File Picker",
        callback: () => {
          new CameraModal(this.app).open();
        }
      });
    });
  }
};
var CameraModal = class extends import_obsidian.Modal {
  constructor(app2) {
    super(app2);
  }
  onOpen() {
    return __async(this, null, function* () {
      const { contentEl } = this;
      const webCamContainer = contentEl.createDiv();
      const videoEl = webCamContainer.createEl("video");
      videoEl.autoplay = true;
      videoEl.muted = true;
      const recordVideoButton = webCamContainer.createEl("button", {
        text: "Start recording"
      });
      const switchCameraButton = webCamContainer.createEl("button", {
        text: "Switch Camera"
      });
      const snapPhotoButton = webCamContainer.createEl("button", {
        text: "Take a snap"
      });
      const filePicker = webCamContainer.createEl("input", {
        placeholder: "Choose image file from system",
        type: "file"
      });
      filePicker.accept = "image/*,video/*";
      filePicker.capture = "camera";
      const filePicker2 = webCamContainer.createEl("input", {
        placeholder: "Choose image file from system",
        type: "file"
      });
      filePicker2.accept = "image/*";
      filePicker2.capture = "camera";
      const chosenFolderPath = "attachments/snaps";
      const chunks = [];
      let recorder = null;
      let 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;
        }
      });
      videoStream = yield getVideoStream();
      if (!videoStream) {
        videoEl.style.display = "none";
        snapPhotoButton.style.display = "none";
        recordVideoButton.style.display = "none";
        switchCameraButton.style.display = "none";
        filePicker2.style.display = "block";
      }
      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 = chosenFolderPath + "/" + fileName;
        const folderExists = app.vault.getAbstractFileByPath(chosenFolderPath);
        if (!folderExists)
          yield app.vault.createFolder(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);
        videoStream && videoStream.getTracks().forEach((track) => {
          track.stop();
        });
        this.close();
      });
      switchCameraButton.onclick = () => __async(this, null, function* () {
        cameraIndex = (cameraIndex + 1) % cameras.length;
        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 = 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(videoStream, {
            mimeType: "video/webm"
          });
        }
        recorder.ondataavailable = (e) => chunks.push(e.data);
        recorder.onstop = (e) => __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() {
    const { contentEl } = this;
    contentEl.empty();
  }
};
//# sourceMappingURL=data:application/json;base64,[encoded data, 12600 characters]
