<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>
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{ $t("center control") }}
            </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: 70vh">
          <q-card class="fit">
            <q-tabs
              v-model="tab"
              dense
              class="text-grey"
              active-color="primary"
              indicator-color="primary"
              align="justify"
              narrow-indicator
            >
              <q-tab
                name="center_control"
                no-caps
                :label="$t('command')"
                :disable="loading"
              />
              <q-tab
                name="connection_setting"
                no-caps
                :label="$t('connection setting')"
                :disable="loading"
              />
            </q-tabs>

            <q-separator />

            <q-tab-panels v-model="tab" animated class="q-pa-none q-ma-none">
              <q-tab-panel name="center_control">
                <q-scroll-area class="full-width" style="height: 58vh">
                  <div
                    class="row full-width q-pt-md"
                    v-for="row of Math.ceil(buttons.length / 4)"
                    :key="row"
                  >
                    <div class="col-3" v-for="col of 4" :key="col">
                      <div
                        class="fit q-px-md"
                        v-if="buttons[(row - 1) * 4 + (col - 1)]"
                      >
                        <q-btn
                          stretch
                          outline
                          no-caps
                          ripple
                          color="primary"
                          class="fit"
                          size="md"
                          :label="buttons[(row - 1) * 4 + (col - 1)].name"
                          @click="
                            centerControlCommand(
                              buttons[(row - 1) * 4 + (col - 1)].number
                            )
                          "
                        >
                          <q-popup-proxy context-menu>
                            <q-list>
                              <q-item
                                clickable
                                v-close-popup
                                @click="
                                  editCenterControlButton(
                                    buttons[(row - 1) * 4 + (col - 1)]
                                  )
                                "
                              >
                                <q-item-section avatar>
                                  <q-icon color="primary" name="edit" />
                                </q-item-section>
                                <q-item-section>{{
                                  $t("edit")
                                }}</q-item-section>
                              </q-item>
                            </q-list>
                          </q-popup-proxy>
                        </q-btn>
                      </div>
                    </div>
                  </div>
                </q-scroll-area>
              </q-tab-panel>

              <q-tab-panel
                name="connection_setting"
                class="q-pa-none q-ma-none fit"
              >
                <q-scroll-area style="height: 57vh">
                  <q-list>
                    <q-item>
                      <q-item-section avatar class="header_label">
                        {{ $t("connection type") }}
                      </q-item-section>
                      <q-item-section>
                        <q-select
                          v-model="current_type"
                          :loading="loading"
                          :disable="loading"
                          :options="[
                            {
                              label: $t('serial port'),
                              value: 'SERIAL_PORT',
                            },
                            {
                              label: $t('tcp'),
                              value: 'TCP',
                            },
                            {
                              label: $t('udp'),
                              value: 'UDP',
                            },
                          ]"
                          emit-value
                          map-options
                          option-value="value"
                          option-label="label"
                        />
                      </q-item-section>
                    </q-item>

                    <div v-if="current_type == 'SERIAL_PORT'">
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("baud rate") }}
                        </q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="serial_port_setting.baud_rate"
                            :loading="loading"
                            :disable="loading"
                            :options="[
                              110, 300, 600, 1200, 2400, 4800, 9600, 14400,
                              19200, 38400, 56000, 57600,
                              115200 /*, 2304000, 380400,
                            460800, 921600,*/,
                            ]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("character size") }}
                        </q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="serial_port_setting.character_size"
                            :loading="loading"
                            :disable="loading"
                            :options="[5, 6, 7, 8]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("parity") }}
                        </q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="serial_port_setting.parity"
                            :loading="loading"
                            :disable="loading"
                            emit-value
                            map-options
                            option-value="value"
                            option-label="label"
                            :options="[
                              {
                                label: 'NONE',
                                value: 0,
                              },
                              {
                                label: 'ODD',
                                value: 1,
                              },
                              {
                                label: 'EVEN',
                                value: 2,
                              },
                            ]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("stop bits") }}
                        </q-item-section>
                        <q-item-section>
                          <q-select
                            v-model="serial_port_setting.stop_bits"
                            :loading="loading"
                            :disable="loading"
                            emit-value
                            map-options
                            option-value="value"
                            option-label="label"
                            :options="[
                              {
                                label: '1 Bit',
                                value: 0,
                              },
                              {
                                label: '1.5 Bit',
                                value: 1,
                              },
                              {
                                label: '2 Bit',
                                value: 2,
                              },
                            ]"
                          />
                        </q-item-section>
                      </q-item>
                    </div>
                    <div v-else-if="current_type == 'TCP'">
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("ip address") }}
                        </q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="tcp_address"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                isIpAddress(val) ||
                                $t('Please input vaild ip address'),
                            ]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("port") }}
                        </q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="tcp_port"
                            max="65535"
                            min="1"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 1 &&
                                  parseInt(val) <= 65535) ||
                                $t(
                                  'the port number must be between 1 and 65535'
                                ),
                            ]"
                            maxlength="5"
                            type="number"
                          />
                        </q-item-section>
                      </q-item>
                    </div>
                    <div v-else-if="current_type == 'UDP'">
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("ip address") }}
                        </q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="udp_address"
                            :rules="[
                              (val) =>
                                (val && val.length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                isIpAddress(val) ||
                                $t('Please input vaild ip address'),
                            ]"
                          />
                        </q-item-section>
                      </q-item>
                      <q-item>
                        <q-item-section avatar class="header_label">
                          {{ $t("port") }}
                        </q-item-section>
                        <q-item-section>
                          <q-input
                            v-model="udp_port"
                            max="65535"
                            min="1"
                            :rules="[
                              (val) =>
                                (val != null &&
                                  val != undefined &&
                                  val.toString().length > 0) ||
                                $t('Please type something'),
                              (val) =>
                                (parseInt(val) >= 1 &&
                                  parseInt(val) <= 65535) ||
                                $t(
                                  'the port number must be between 1 and 65535'
                                ),
                            ]"
                            maxlength="5"
                            type="number"
                          />
                        </q-item-section>
                      </q-item>
                    </div>
                    <div v-else>
                      <span class="h2">{{ $t("unknow type") }}</span>
                    </div>
                  </q-list>
                </q-scroll-area>
                <q-separator />
                <div class="row">
                  <q-space />
                  <div class="col-auto">
                    <q-btn
                      no-caps
                      flat
                      :label="$t('revert')"
                      :loading="loading"
                      color="primary"
                      @click="onRevertConfig"
                    />
                  </div>
                  <div class="col-auto">
                    <q-btn
                      flat
                      no-caps
                      :label="$t('submit')"
                      :loading="loading"
                      color="primary"
                      @click="onSubmitConfig"
                    />
                  </div>
                </div>
              </q-tab-panel>
            </q-tab-panels>
          </q-card>
        </q-card-section>
      </q-form>
    </q-card>
  </q-dialog>
  <center-control-button-dialog ref="center_control_button_dialog" />
</template>

<style scoped>
.header_label {
  width: 20%;
}
</style>

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

import {
  ESerialPortFlowControlHelper,
  ESerialPortParityHelper,
  ESerialPortStopBitsHelper,
  SerialPortConfigEntity,
} from "src/entities/SerialPortConfigEntity";
import { Protocol } from "src/entities/WSProtocol";
import ValidationUtil from "src/common/ValidationUtil";

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

    let show_dialog = ref(false);
    let loading = ref(false);
    let tab = ref("center_control");

    const buttons: Ref<ExternalControlTableEntity[]> = ref([]);
    const serial_port_setting: SerialPortConfigEntity = reactive(
      new SerialPortConfigEntity()
    );
    const old_serial_port_setting = new SerialPortConfigEntity();

    const current_type = ref("SERIAL_PORT");
    const tcp_address = ref("192.168.2.2");
    const tcp_port = ref("10000");
    const udp_address = ref("192.168.2.2");
    const udp_port = ref("10000");

    let old_current_type = "SERIAL_PORT";
    let old_tcp_address = "192.168.2.2";
    let old_tcp_port = "10000";
    let old_udp_address = "192.168.2.2";
    let old_udp_port = "10000";

    let old_response: Protocol.RpcGetExternalControlSerialPortConfigResponseEntity =
      new Protocol.RpcGetExternalControlSerialPortConfigResponseEntity();

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

    return {
      show_dialog,
      loading,
      tab,
      buttons,
      serial_port_setting,
      center_control_button_dialog,
      current_type,
      tcp_address,
      tcp_port,
      udp_address,
      udp_port,
      copyToClipboard,
      loga(a: any) {
        console.log(a);
      },
      async showDialog() {
        show_dialog.value = true;
        loading.value = true;

        try {
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.getExternalControlDatas();
          if (response) {
            const btns = response.datas;
            const compare = (property: any) => {
              return function (a: any, b: any) {
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;
              };
            };
            btns.sort(compare("number"));
            buttons.value = btns;
          }
        } catch {}
        try {
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.getExternalControlSerialPortConfig();
          if (response) {
            serial_port_setting.baud_rate = response.serial_port.baud_rate;
            serial_port_setting.character_size =
              response.serial_port.character_size;
            serial_port_setting.parity = ESerialPortParityHelper.fromString(
              (<unknown>response.serial_port.parity) as string
            );
            serial_port_setting.stop_bits =
              ESerialPortStopBitsHelper.fromString(
                (<unknown>response.serial_port.stop_bits) as string
              );
            serial_port_setting.flow_control =
              ESerialPortFlowControlHelper.fromString(
                (<unknown>response.serial_port.flow_control) as string
              );

            current_type.value = response.current_type;
            tcp_address.value = response.tcp_address;
            tcp_port.value = response.tcp_port.toString();
            udp_address.value = response.udp_address;
            udp_port.value = response.udp_port.toString();

            old_serial_port_setting.baud_rate = serial_port_setting.baud_rate;
            old_serial_port_setting.character_size =
              serial_port_setting.character_size;
            old_serial_port_setting.parity = serial_port_setting.parity;
            old_serial_port_setting.stop_bits = serial_port_setting.stop_bits;
            old_serial_port_setting.flow_control =
              serial_port_setting.flow_control;

            old_current_type = current_type.value;
            old_tcp_address = tcp_address.value;
            old_tcp_port = tcp_port.value;
            old_udp_address = udp_address.value;
            old_udp_port = udp_port.value;

            old_response = response;
          }
        } catch {}

        loading.value = false;
      },
      resetData() {
        loading.value = false;
      },

      async onRevertConfig() {
        serial_port_setting.baud_rate = old_serial_port_setting.baud_rate;
        serial_port_setting.character_size =
          old_serial_port_setting.character_size;
        serial_port_setting.parity = old_serial_port_setting.parity;
        serial_port_setting.stop_bits = old_serial_port_setting.stop_bits;
        serial_port_setting.flow_control = old_serial_port_setting.flow_control;

        tcp_address.value = old_tcp_address;
        tcp_port.value = old_tcp_port;

        udp_address.value = old_udp_address;
        udp_port.value = old_udp_port;
        current_type.value = old_current_type;
      },

      async onSubmitConfig() {
        loading.value = true;
        let success = false;

        let request_current_type = current_type.value;
        if (
          request_current_type != "SERIAL_PORT" &&
          request_current_type != "UDP" &&
          request_current_type != "TCP"
        ) {
          request_current_type = "SERIAL_PORT";
        }

        try {
          let request_serial_prot_config =
            old_response.serial_port ?? new SerialPortConfigEntity();
          let request_tcp_address = old_response.tcp_address ?? "192.168.2.2";
          let request_tcp_port = old_response.tcp_port ?? 1000;
          let request_udp_address = old_response.udp_address ?? "192.168.2.2";
          let request_udp_port = old_response.udp_port ?? 1000;

          switch (request_current_type) {
            case "SERIAL_PORT":
              request_serial_prot_config.baud_rate =
                serial_port_setting.baud_rate;
              request_serial_prot_config.character_size =
                serial_port_setting.character_size;
              (<any>request_serial_prot_config.parity) =
                ESerialPortParityHelper.toString(serial_port_setting.parity);
              (<any>request_serial_prot_config.stop_bits) =
                ESerialPortStopBitsHelper.toString(
                  serial_port_setting.stop_bits
                );
              (<any>request_serial_prot_config.flow_control) =
                ESerialPortFlowControlHelper.toString(
                  serial_port_setting.flow_control
                );
              break;
            case "TCP":
              {
                request_tcp_address = tcp_address.value;
                const temp = parseInt(tcp_port.value);
                if (isNaN(temp)) {
                  request_tcp_port = 1000;
                } else {
                  request_tcp_port = temp;
                }
              }
              break;
            case "UDP":
              {
                request_udp_address = udp_address.value;
                const temp = parseInt(udp_port.value);
                if (isNaN(temp)) {
                  request_udp_port = 1000;
                } else {
                  request_udp_port = temp;
                }
              }
              break;
          }

          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.setExternalControlSerialPortConfig(
              request_serial_prot_config,
              request_tcp_address,
              request_tcp_port,
              request_udp_address,
              request_udp_port,
              request_current_type
            );

          if (response) {
            success = response.success;

            old_serial_port_setting.baud_rate = serial_port_setting.baud_rate;
            old_serial_port_setting.character_size =
              serial_port_setting.character_size;
            old_serial_port_setting.parity = serial_port_setting.parity;
            old_serial_port_setting.stop_bits = serial_port_setting.stop_bits;
            old_serial_port_setting.flow_control =
              serial_port_setting.flow_control;

            old_current_type = current_type.value;
            old_tcp_address = tcp_address.value;
            old_tcp_port = tcp_port.value;
            old_udp_address = udp_address.value;
            old_udp_port = udp_port.value;
            old_current_type = current_type.value;
          }
        } catch {}

        $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,
        });
        loading.value = false;
      },
      async centerControlCommand(number?: number) {
        let success = false;
        try {
          if (
            typeof number != "undefined" &&
            number != null &&
            !isNaN(number)
          ) {
            const resposne = await GlobalData.getInstance()
              .getCurrentClient()
              ?.callExternalControlData(number);

            if (resposne) {
              success = resposne.success;
            }
          }
        } catch (e) {
          console.error(e);
        }
        $q.notify({
          color: success ? "positive" : "negative",
          icon: success ? "done" : "warning",
          message:
            $t.t("send command") +
            $t.t(success ? "success" : "failed") +
            (success
              ? ""
              : "," + $t.t(" ") + $t.t("please check connection config")) +
            "!",
          position: "top",
          timeout: 2500,
        });
      },
      async editCenterControlButton(data?: ExternalControlTableEntity) {
        if (data) {
          if (center_control_button_dialog.value) {
            const { name, command, icon } = data;
            let success = false;
            try {
              const result =
                await center_control_button_dialog.value.showDialogAsync(data);
              if (result) {
                if (result.name) {
                  data.name = result.name;
                }
                if (result.command) {
                  data.command = result.command;
                }
                if (result.icon) {
                  data.icon = result.icon;
                }
                const response = await GlobalData.getInstance()
                  .getCurrentClient()
                  ?.editExternalControlData(data);
                if (response) {
                  success = response.success;
                }
              } else {
                // cancel
                return;
              }
            } catch {}
            if (!success) {
              data.name = name;
              data.command = command;
              data.icon = icon;
            }
            $q.notify({
              color: success ? "positive" : "negative",
              icon: success ? "done" : "warning",
              message:
                $t.t("edit button") +
                (success ? $t.t("success") : $t.t("fail")) +
                "!",
              position: "top",
              timeout: 1500,
            });
          } else {
            console.log("center_control_button_dialog is null");
          }
        }
      },
      isIpAddress(str: string) {
        return ValidationUtil.isIpAddress(str);
      },
    };
  },
});
</script>
