<!-- $Id: orcForm.vue,v 1 2026/04/30 15:36:40 qvarin Exp $ -->

<template>
  <form class="form-admin" action="" method="POST" @submit.prevent="submit">
    <h3>{{ messages.get("ocr", "admin_ocr_config") }}</h3>

    <div class="form-contenu">
      <div class="row">
        <div class="colonne4">
          <label for="ocr_service">
            {{ messages.get("ocr", "admin_ocr_config_service") }}
            <span :aria-label="messages.get('common', 'required_message')">
              {{ messages.get("common", "required_symbol") }}
            </span>
          </label>
        </div>
        <div class="colonne8">
          <select name="ocr_service" id="ocr_service" v-model.number="service" required>
            <option value="1">{{ messages.get("ocr", "admin_ocr_config_service_1") }}</option>
            <option value="2">{{ messages.get("ocr", "admin_ocr_config_service_2") }}</option>
          </select>
        </div>
      </div>

      <component :is="componentForm" :config="values" @update:config="updateConfig" />

      <div class="row">
        <br />
        <div class="left">
          <input @click="cancel" class="bouton" type="button" :value="messages.get('ocr', 'admin_ocr_cancel')" />
          <input class="bouton" type="submit" :value="messages.get('ocr', 'admin_ocr_save')" />
        </div>
      </div>
    </div>
  </form>
</template>

<script>
import configForm from "./configForm.vue";
import configServerForm from "./configServerForm.vue";

export default {
  props: {
    config: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    configForm,
    configServerForm,
  },

  data: function() {
    return {
      values: {},
      service: 0,
    };
  },
  mounted() {
    this.$set(this, "values", { ...this.config });
    this.service = this.config?.service ?? 0;
  },
  computed: {
    componentForm() {
      switch (this.service) {
        case 1:
          return "configForm";
        case 2:
          return "configServerForm";
        default:
          return "";
      }
    },
  },
  methods: {
    updateConfig(config) {
      this.values = config;
    },
    cancel() {
      document.location = "./admin.php?categ=ocr";
    },
    submit(event) {
      event.preventDefault();

      this.ws
        .post("config", "save", {
          ...this.values,
          service: this.service,
        })
        .then((response) => {
          if (response.error) {
            this.notif.error(this.messages.get("common", "failed_save"));
          } else {
            this.notif.info(this.messages.get("common", "success_save"));
          }
        })
        .catch((_) => {
          this.notif.error(this.messages.get("common", "failed_save"));
        });

      return false;
    },
  },
};
</script>
