<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (!loading && evt.keyCode == 27) {
          show_dialog = false;
        }
      }
    "
  >
    <q-card class="overflow-hidden" style="max-width: 60vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ dialog_status == 0 ? $t("add") : $t("edit")
              }}{{ $t("button") }}
            </div>
            <q-space />
            <div>
              <q-btn
                :loading="loading"
                :disable="loading"
                flat
                round
                icon="close"
                color="red"
                v-close-popup
              >
                <q-tooltip>
                  {{ $t("close") }}
                </q-tooltip>
              </q-btn>
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section class="scroll" style="width: 60vw; height: 50vh">
          <q-list>
            <q-item>
              <q-item-section avatar class="header_label">
                {{ $t("name") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  v-model="button_name"
                  :loading="loading"
                  :disable="loading"
                  lazy-rules
                  :rules="[
                    (val) =>
                      (val && val.toString().length > 0) ||
                      $t('Please type something'),
                  ]"
                />
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar class="header_label">
                {{ $t("command") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  v-model="button_command"
                  type="textarea"
                  :loading="loading"
                  :disable="loading"
                  :rules="[
                    (val) =>
                      isHexStr(val) ||
                      $t('Please input vaild hex str') +
                        ' \t' +
                        $t('example') +
                        ': 0x00 0x01 0x02 0x03',
                  ]"
                  :hint="$t('example') + ': 0x00 0x01 0x02 0x03'"
                />
              </q-item-section>
            </q-item>
            <q-item v-if="false">
              <q-item-section avatar class="header_label">
                {{ $t("icon") }}
              </q-item-section>
              <q-item-section>
                <q-input
                  v-model="button_icon"
                  :loading="loading"
                  :disable="loading"
                />
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            ref="cancel"
            flat
            :label="$t('Cancel')"
            no-caps
            :loading="loading"
            v-close-popup
            color="primary"
          />

          <q-btn
            ref="accept"
            flat
            :label="$t('Accept')"
            no-caps
            :loading="loading"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.header_label {
  width: 10%;
}
.header_label_2 {
  width: 10%;
  align-items: center;
}
</style>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { useStore } from "src/store";
import { useQuasar, copyToClipboard } from "quasar";
import { useI18n } from "vue-i18n";

import { ExternalControlTableEntity } from "src/entities/ExternalControlTableEntity";
import ValidationUtil from "src/common/ValidationUtil";

export default defineComponent({
  name: "ComponentCenterControlButtonDialog",
  components: {},
  setup() {
    let $store = useStore();
    let $q = useQuasar();
    let $t = useI18n();

    let show_dialog = ref(false);
    let loading = ref(false);

    const button_name = ref("");
    const button_command = ref("");
    const button_icon = ref("");
    const dialog_status = ref(0); // 0: add 1: edit

    let _reject: any = null;
    let _resolve: any = null;

    return {
      show_dialog,
      loading,
      button_name,
      dialog_status,
      button_command,
      button_icon,
      copyToClipboard,
      loga(a: any) {
        console.log(a);
      },
      async showDialogAsync(in_data?: ExternalControlTableEntity) {
        if (_resolve) {
          _resolve(null);
        } else if (_reject) {
          _reject(null);
        }
        return new Promise((resolve, reject) => {
          _reject = reject;
          _resolve = resolve;
          if (in_data) {
            dialog_status.value = 1;
            button_name.value =
              in_data.name ?? $t.t("new button") + (in_data.number ?? 1);
            const temp_command = in_data.command ?? "";
            button_icon.value = "";

            let target_show_command = "";
            for (const item of temp_command) {
              try {
                let temp_str = item.toString(16).toUpperCase();
                if (temp_str.length == 1) {
                  temp_str = "0" + temp_str;
                }
                target_show_command += "0x" + temp_str + " ";
              } catch {}
            }
            button_command.value = target_show_command;
          } else {
            dialog_status.value = 0;
            button_name.value = $t.t("new button") + "1";
            button_command.value = "";
            button_icon.value = "";
          }

          show_dialog.value = true;
        });
      },
      resetData() {
        loading.value = false;
        dialog_status.value = 0;
        button_name.value = "";
        button_command.value = "";
        button_icon.value = "";
        if (_resolve) {
          _resolve(null);
        } else if (_reject) {
          _reject(null);
        }
        _reject = null;
        _resolve = null;
      },
      onSubmit() {
        const command = [];
        for (const item of button_command.value.trim().split(" ")) {
          try {
            const v = parseInt(item);
            if (!isNaN(v)) {
              command.push(v);
            }
          } catch {}
        }

        const data = {
          name: button_name.value,
          command,
          icon: button_icon.value,
        };

        if (_resolve) {
          _resolve(data);
        } else if (_reject) {
          _reject(data);
        }
        show_dialog.value = false;
      },
      isHexStr(val: string) {
        return ValidationUtil.isHexStr(val);
      },
    };
  },
});
</script>
