<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; max-height: 75vh"
        >
          <q-card-section class="fit" v-if="false">
            <q-card>
              <q-card-section>
                <q-item class="q-pa-none">
                  <q-item-section avatar class="header_label_2 text-left">{{
                    $t("host name") + ":"
                  }}</q-item-section>
                  <q-item-section>
                    <q-input
                      v-model="host_name"
                      maxlength="20"
                      :rules="[
                        (val) =>
                          (val && val.length > 0) ||
                          $t('Please type something'),
                        (val) =>
                          isEnglishOrNum(val) ||
                          $t(
                            'Host names can only be numbers and letters and _-'
                          ),
                      ]"
                      lazy-rules
                    />
                  </q-item-section>
                </q-item>
              </q-card-section>
            </q-card>
          </q-card-section>
          <q-card-section>
            <q-table
              ref="advance_ip_table"
              class="advance-ip-table"
              :title="$t('ip address')"
              :rows="advance_ip_rows"
              :columns="advance_ip_columns"
              row-key="uuid"
              :hide-bottom="true"
              selection="single"
              virtual-scroll
              :virtual-scroll-item-size="48"
              :virtual-scroll-sticky-size-start="48"
              :rows-per-page-options="[0]"
              @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"
                  no-caps
                  :label="$t('add row')"
                  class="col-2"
                  @click="advance_ip_addRow"
                />
                <q-btn
                  :disable="advance_ip_table_selected.length == 0"
                  flat
                  no-caps
                  color="primary"
                  :label="$t('edit row')"
                  class="col-2"
                  @click="advance_ip_editRow"
                />
                <q-btn
                  :disable="advance_ip_table_selected.length == 0"
                  flat
                  no-caps
                  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-section class="q-py-none q-my-none">
            <q-card>
              <q-form>
                <q-list class="q-pb-md">
                  <q-item>
                    <q-item-section avatar class="header_label">
                      {{ $t("http") }}{{ $t(" ") }}{{ $t("port") }}:
                    </q-item-section>
                    <q-item-section>
                      <q-input
                        type="number"
                        v-model="http_port"
                        max="65535"
                        maxlength="5"
                        min="0"
                        :rules="[
                          (val) =>
                            (val != null &&
                              val != undefined &&
                              val.toString().length > 0) ||
                            $t('Please type something'),
                          (val) =>
                            (parseInt(val) >= 0 && parseInt(val) <= 65535) ||
                            $t('the port number must be between 0 and 65535'),
                        ]"
                      />
                    </q-item-section>
                    <q-item-section>
                      <q-item-label>
                        ({{ $t($t("current real")) }}{{ $t(" ") }}{{ $t("http")
                        }}{{ $t(" ") }}{{ $t("port") }}: {{ real_http_port }})
                      </q-item-label>
                    </q-item-section>
                    <q-item-section avatar>
                      <q-btn
                        :disable="old_http_port == http_port"
                        no-caps
                        :label="$t('apply')"
                        @click="commitHttpPort"
                      />
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section avatar class="header_label">
                      {{ $t("control") }}{{ $t(" ") }}{{ $t("port") }}:
                    </q-item-section>
                    <q-item-section>
                      <q-input
                        maxlength="5"
                        type="number"
                        v-model="websocket_port"
                        max="65535"
                        min="0"
                        :rules="[
                          (val) =>
                            (val != null &&
                              val != undefined &&
                              val.toString().length > 0) ||
                            $t('Please type something'),
                          (val) =>
                            (parseInt(val) >= 0 && parseInt(val) <= 65535) ||
                            $t('the port number must be between 0 and 65535'),
                        ]"
                      />
                    </q-item-section>
                    <q-item-section>
                      <q-item-label>
                        ({{ $t($t("current real")) }}{{ $t(" ")
                        }}{{ $t("control") }}{{ $t(" ") }}{{ $t("port") }}:
                        {{ real_websocket_port }})
                      </q-item-label>
                    </q-item-section>
                    <q-item-section avatar>
                      <q-btn
                        :disable="old_websocket_port == websocket_port"
                        no-caps
                        :label="$t('apply')"
                        @click="commitWebsocketPort"
                      />
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-form>
            </q-card>
          </q-card-section>
        </q-card-section>

        <q-separator />

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

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

<style lang="sass">
.advance-ip-table
  /* height or max-height is important */
  max-height: 45vh
  min-height: 30vh

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th /* bg color is important for th; just specify one */
    background-color: #fff

  thead tr th
    position: sticky
    z-index: 1
  /* this will be the loading indicator */
  thead tr:last-child th
    /* height of all previous header rows */
    top: 48px
  thead tr:first-child th
    top: 0
</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";
import { AdvancedIpAddressEntity } from "src/entities/AdvancedIpAddressEntity";
import { api } from "src/boot/axios";
import { HttpProtocol } from "src/entities/HttpProtocol";
import ValidationUtil from "src/common/ValidationUtil";

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<AdvancedIpAddressEntity[]> = ref([]);
    const host_name = ref("player");

    const http_port = ref(GlobalData.kDefaultHttpPort);
    const old_http_port = ref(GlobalData.kDefaultHttpPort);
    const real_http_port = ref(GlobalData.kDefaultHttpPort);
    const websocket_port = ref(GlobalData.kDefaultWebsocektPort);
    const old_websocket_port = ref(GlobalData.kDefaultWebsocektPort);
    const real_websocket_port = ref(GlobalData.kDefaultWebsocektPort);

    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<AdvancedIpAddressEntity[]> = ref([]);

    let _resolove: any = null;

    return {
      show_dialog,
      advanced_ip_address_dialog,
      advance_ip_columns,
      advance_ip_rows,
      advance_ip_table_selected,
      host_name,
      http_port,
      old_http_port,
      real_http_port,
      websocket_port,
      old_websocket_port,
      real_websocket_port,
      loga(a: any) {
        console.log(a);
      },
      async showDialogAsync(_data: AdvancedIpAddressEntity[]) {
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
        return new Promise((resolove) => {
          _resolove = resolove;

          GlobalData.getInstance()
            .getCurrentClient()
            ?.getSystemNetworkInfo()
            .then((response) => {
              if (response) {
                host_name.value = (response.host_name ?? "player").trim();
              }
            });

          if (Array.isArray(_data)) {
            for (const item of _data) {
              if (item) {
                (<any>item).uuid = uid();
                advance_ip_rows.value.push(item);
              }
            }
          }

          {
            const port = parseInt(
              GlobalData.getInstance().applicationConfig?.httpserver_port ??
                "80"
            );
            if (!isNaN(port) && port != Infinity) {
              http_port.value = port;
              old_http_port.value = port;
            } else {
              http_port.value = 80;
              old_http_port.value = 80;
            }
          }

          {
            const port = parseInt(
              GlobalData.getInstance().applicationConfig?.websocket_port ??
                GlobalData.kDefaultWebsocektPort.toString()
            );
            if (!isNaN(port) && port != Infinity) {
              websocket_port.value = port;
              old_websocket_port.value = port;
            } else {
              websocket_port.value = GlobalData.kDefaultWebsocektPort;
              old_websocket_port.value = GlobalData.kDefaultWebsocektPort;
            }
          }

          {
            api
              .get(HttpProtocol.RequestPathGetAllPort)
              .then((response) => {
                if (response && typeof response.data != "undefined") {
                  if (typeof response.data.http == "number") {
                    real_http_port.value = response.data.http;
                  } else if (typeof response.data.http == "string") {
                    const temp = parseInt(response.data.http);
                    if (!isNaN(temp) && temp != Infinity) {
                      real_http_port.value = temp;
                    }
                  }

                  if (typeof response.data.websocket == "number") {
                    real_websocket_port.value = response.data.websocket;
                  } else if (typeof response.data.websocket == "string") {
                    const temp = parseInt(response.data.websocket);
                    if (!isNaN(temp) && temp != Infinity) {
                      real_websocket_port.value = temp;
                    }
                  }
                }
              })
              .catch((e) => {
                console.log(e);
              });
          }
          show_dialog.value = true;
        });
      },
      resetData() {
        if (_resolove) {
          _resolove();
          _resolove = null;
        }
        advance_ip_rows.value = [];
        advance_ip_table_selected.value = [];
        host_name.value = "player";
      },

      async onSubmit() {
        // let success = false;

        try {
          if (_resolove) {
            try {
              _resolove({
                ip_address_list: advance_ip_rows.value,
                host_name: host_name.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) {
          const push_data = new AdvancedIpAddressEntity();
          (<any>push_data).uuid = uid();
          push_data.ip_address = data.ip_address;
          push_data.gateway = data.gateway;
          push_data.netmask = data.netmask;
          // push_data.dns1= data.dns1
          // push_data.dns2= data.dns2

          advance_ip_rows.value.push(push_data);
        }
      },
      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;
          }
        }
      },
      commitHttpPort() {
        $q.dialog({
          title: $t.t("Confirm"),
          message: $t.t("are you sure to change the http port") + "?",
          ok: {
            label: $t.t("ok"),
            noCaps: true,
            flat: true,
          },
          cancel: {
            label: $t.t("cancel"),
            noCaps: true,
            flat: true,
          },
          persistent: true,
        }).onOk(() => {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.setHttpPort(http_port.value);
          $q.dialog({
            title: $t.t("Confirm"),
            message:
              $t.t(
                "the new http port takes effect after the software is restarted"
              ) +
              "," +
              $t.t("restart now") +
              "?",
            ok: {
              label: $t.t("ok"),
              noCaps: true,
              flat: true,
            },
            cancel: {
              label: $t.t("cancel"),
              noCaps: true,
              flat: true,
            },
            persistent: true,
          }).onOk(() => {
            GlobalData.getInstance().getCurrentClient()?.restartDevice();
          });
        });
      },
      commitWebsocketPort() {
        $q.dialog({
          title: $t.t("Confirm"),
          message: $t.t("are you sure to change the control port") + "?",
          ok: {
            label: $t.t("ok"),
            noCaps: true,
            flat: true,
          },
          cancel: {
            label: $t.t("cancel"),
            noCaps: true,
            flat: true,
          },
          persistent: true,
        }).onOk(() => {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.setWebsocketPort(websocket_port.value);
          $q.dialog({
            title: $t.t("Confirm"),
            message:
              $t.t(
                "the new control port takes effect after the software is restarted"
              ) +
              "," +
              $t.t("restart now") +
              "?",
            ok: {
              label: $t.t("ok"),
              noCaps: true,
              flat: true,
            },
            cancel: {
              label: $t.t("cancel"),
              noCaps: true,
              flat: true,
            },
            persistent: true,
          }).onOk(() => {
            GlobalData.getInstance().getCurrentClient()?.restartDevice();
          });
        });
      },
      isEnglishOrNum(str: string) {
        return ValidationUtil.isEnglishOrNum(str);
      },
    };
  },
});
</script>
