<template>
  <q-dialog
    persistent
    v-model="show_dialog"
    @before-hide="resetData"
    @keydown="
      (evt) => {
        if (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">
              {{ $t("advanced network setting") }}
            </div>
            <q-space />
            <div>
              <q-btn flat round icon="close" color="red" v-close-popup>
                <q-tooltip>
                  {{ $t("close") }}
                </q-tooltip>
              </q-btn>
            </div>
          </div>
        </q-card-section>

        <q-card-section
          class="scroll q-pa-xs q-ma-none"
          style="width: 60vw; height: 65vh"
        >
          <q-card class="fit">
            <q-card-section class="q-pa-none fit">
              <q-table
                class="fit"
                ref="advance_ip_table"
                :title="$t('ip address')"
                :rows="advance_ip_rows"
                :columns="advance_ip_columns"
                row-key="uuid"
                :hide-bottom="true"
                :selection="'single'"
                @row-click="
                  (evt, row, index) => {
                    if (advance_ip_table_selected.length) {
                      advance_ip_table_selected =
                        advance_ip_table_selected[0].uuid == row.uuid
                          ? []
                          : [row];
                    } else {
                      advance_ip_table_selected = [row];
                    }
                  }
                "
                v-model:selected="advance_ip_table_selected"
              >
                <template v-slot:top="props">
                  <div class="col-2 q-table__title">{{ $t("ip address") }}</div>

                  <q-space />

                  <q-btn
                    flat
                    color="primary"
                    :label="$t('add row')"
                    class="col-2"
                    @click="advance_ip_addRow"
                  />
                  <q-btn
                    :disable="advance_ip_table_selected.length == 0"
                    flat
                    color="primary"
                    :label="$t('edit row')"
                    class="col-2"
                    @click="advance_ip_editRow"
                  />
                  <q-btn
                    :disable="advance_ip_table_selected.length == 0"
                    flat
                    color="primary"
                    :label="$t('delete row')"
                    class="col-2"
                    @click="
                      advance_ip_table_selected.length &&
                        (advance_ip_rows = advance_ip_rows.filter(
                          (element) =>
                            element && element != advance_ip_table_selected[0]
                        )) &&
                        (advance_ip_table_selected = [])
                    "
                  />
                </template>
              </q-table>
            </q-card-section>
          </q-card>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn flat :label="$t('Cancel')" color="primary" v-close-popup />
          <q-btn
            ref="accept"
            flat
            :label="$t('Accept')"
            type="submit"
            color="primary"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
  <advanced-ip-address-dialog ref="advanced_ip_address_dialog" />
</template>

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

<script lang="ts">
import { defineComponent, ref, Ref, reactive } from "vue";
import { useStore } from "src/store";
import { useQuasar, copyToClipboard, uid } from "quasar";
import { useI18n } from "vue-i18n";
import GlobalData from "src/common/GlobalData";
import AdvancedIpAddressDialog from "src/components/AdvancedIpAddressDialog.vue";

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

    const advanced_ip_address_dialog: Ref<any> = ref(null);

    let show_dialog = ref(false);

    const advance_ip_table_selected: Ref<any> = ref([]);

    const advance_ip_columns = [
      {
        name: "ip_address",
        required: true,
        label: $t.t("ip address"),
        align: "left",
        field: "ip_address",
      },
      {
        name: "netmask",
        align: "left",
        label: $t.t("netmask"),
        field: "netmask",
      },
      {
        name: "gateway",
        align: "left",
        label: $t.t("gateway"),
        field: "gateway",
      },
      {
        name: "dns1",
        align: "left",
        field: "dns1",
        label: $t.t("dns server") + " 1",
      },
      {
        name: "dns2",
        align: "left",
        field: "dns2",
        label: $t.t("dns server") + " 2",
      },
    ];

    const advance_ip_rows: Ref<any> = ref([]);

    const isIpAddress = (str: string) => {
      return (
        str == "localhost" ||
        /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(
          str
        )
      );
    };

    let _resolove: any = null;

    return {
      show_dialog,
      advanced_ip_address_dialog,
      advance_ip_columns,
      advance_ip_rows,
      advance_ip_table_selected,
      loga(a: any) {
        console.log(a);
      },
      async showDialogAsync(_data: any) {
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
        return new Promise((resolove) => {
          show_dialog.value = true;
        });
      },
      resetData() {
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
        advance_ip_rows.value = [];
        advance_ip_table_selected.value = [];
      },

      async onSubmit() {
        let success = false;

        try {
          if (_resolove) {
            try {
              _resolove({
                ip_address_list: advance_ip_rows.value,
              });
            } catch {
              _resolove(null);
            }
          }
        } catch {}

        show_dialog.value = false;

        // $q.notify({
        //   color: success ? "positive" : "negative",
        //   icon: success ? "done" : "warning",
        //   message:
        //     $t.t("set serialport") +
        //     (success ? $t.t("success") : $t.t("fail")) +
        //     "!",
        //   position: "top",
        //   timeout: 1500,
        // });
      },
      async advance_ip_addRow() {
        const data: any =
          await advanced_ip_address_dialog.value.showDialogAsync(
            "edit",
            null,
            advance_ip_rows.value.map((element: any) => element.ip_address)
          );
        if (data) {
          advance_ip_rows.value.push({
            uuid: uid(),
            ip_address: data.ip_address,
            gateway: data.gateway,
            netmask: data.netmask,
            dns1: data.dns1,
            dns2: data.dns2,
          });
        }
      },
      async advance_ip_editRow() {
        if (advance_ip_table_selected.value.length) {
          const data: any =
            await advanced_ip_address_dialog.value.showDialogAsync(
              "edit",
              advance_ip_table_selected.value[0],
              advance_ip_rows.value.map((element: any) => element.ip_address)
            );
          if (data) {
            advance_ip_table_selected.value[0].ip_address = data.ip_address;
            advance_ip_table_selected.value[0].gateway = data.gateway;
            advance_ip_table_selected.value[0].netmask = data.netmask;
            advance_ip_table_selected.value[0].dns1 = data.dns1;
            advance_ip_table_selected.value[0].dns2 = data.dns2;
          }
        }
      },
    };
  },
});
</script>
