<template>
  <div>
    <div id="container">
      <el-form :model="form" label-width="auto">
        <el-form-item label="Issuer">
          <el-input v-model="form.issuer" />
        </el-form-item>
        <el-form-item label="Username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="Secret">
          <el-input v-model="form.secret" />
        </el-form-item>
        <el-form-item label="Notes">
          <el-input v-model="form.notes" />
        </el-form-item>
      </el-form>
      <el-button @click="createSecret" type="primary" v-if="showAddMore"
        >Save & Add More</el-button
      >
      <el-button
        @click="
          createSecret();
          closeDialog();
        "
        type="primary"
        >Save & Close</el-button
      >
    </div>
  </div>
</template>

<script>
export default {
  props: {
    editSecret: Object,
  },
  data() {
    return {
      title: "Create Secret",
      apiBaseUrl: "http://localhost:8000",
      id: null,
      form: {
        issuer: "",
        username: "",
        secret: "",
        notes: "",
      },
      method: "POST",
      showAddMore: true,
    };
  },

  methods: {
    async createSecret() {
      const url = `${this.apiBaseUrl}/secret`;
      const token = sessionStorage.getItem("token");
      const bodyData = { data: btoa(JSON.stringify(this.form)) };
      if (this.method === "PUT") {
        bodyData["id"] = this.id;
      }
      const requestOptions = {
        method: this.method,
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(bodyData),
      };
      console.log(requestOptions);
      await fetch(url, requestOptions)
        .then((response) => response.json())
        .then((data) => console.log(data));
    },

    closeDialog() {
      (this.form.issuer = ""),
        (this.form.username = ""),
        (this.form.notes = ""),
        (this.form.secret = "");
      this.$emit("close", true);
    },
  },

  created() {
    // console.log(this.editSecret.id);
    if (this.editSecret) {
      this.id = this.editSecret.id;
      this.form.issuer = this.editSecret.issuer;
      this.form.username = this.editSecret.username;
      this.form.secret = this.editSecret.secret;
      this.form.notes = this.editSecret.notes;
      this.method = "PUT";
      this.showAddMore = false;
    }
  },
};
</script>

<style>
h3 {
  margin-top: 1rem;
  font-weight: 700;
  font-size: 1.5rem;
  color: teal;
}
</style>
