<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"
                :label="$t('control')"
                :disable="loading"
              />
              <q-tab
                name="serial_port_setting"
                :label="$t('serial port 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
                          ripple
                          color="primary"
                          class="fit"
                          size="md"
                          :label="buttons[(row - 1) * 4 + (col - 1)].name"
                          @click="
                            centerControlCommand(
                              buttons[(row - 1) * 4 + (col - 1)].uuid
                            )
                          "
                        >
                          <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="serial_port_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("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,
                          ] /*[
                          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>
                  </q-list>
                </q-scroll-area>
                <q-separator />
                <div class="row">
                  <q-space />
                  <div class="col-auto">
                    <q-btn
                      flat
                      :label="$t('revert')"
                      :loading="loading"
                      color="primary"
                      @click="onRevertSerialportConfig"
                    />
                  </div>
                  <div class="col-auto">
                    <q-btn
                      flat
                      :label="$t('submit')"
                      :loading="loading"
                      color="primary"
                      @click="onSubmitSerialportConfig"
                    />
                  </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: 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 } 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";

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 center_control_button_dialog: Ref<any> = ref(null);

    return {
      show_dialog,
      loading,
      tab,
      buttons,
      serial_port_setting,
      center_control_button_dialog,
      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.config.baud_rate;
            serial_port_setting.character_size = response.config.character_size;
            serial_port_setting.parity = ESerialPortParityHelper.fromString(
              (<unknown>response.config.parity) as string
            );
            serial_port_setting.stop_bits =
              ESerialPortStopBitsHelper.fromString(
                (<unknown>response.config.stop_bits) as string
              );
            serial_port_setting.flow_control =
              ESerialPortFlowControlHelper.fromString(
                (<unknown>response.config.flow_control) as string
              );

            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;
          }
        } catch {}

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

      async onRevertSerialportConfig() {
        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;
      },

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

        try {
          const request_param = new SerialPortConfigEntity();
          request_param.baud_rate = serial_port_setting.baud_rate;
          request_param.character_size = serial_port_setting.character_size;
          (<any>request_param.parity) = ESerialPortParityHelper.toString(
            serial_port_setting.parity
          );
          (<any>request_param.stop_bits) = ESerialPortStopBitsHelper.toString(
            serial_port_setting.stop_bits
          );
          (<any>request_param.flow_control) =
            ESerialPortFlowControlHelper.toString(
              serial_port_setting.flow_control
            );
          const response = await GlobalData.getInstance()
            .getCurrentClient()
            ?.setExternalControlSerialPortConfig(request_param);

          if (response) {
            success = response.success;
            console.log(response);
            console.log(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;
          }
        } 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;
      },
      centerControlCommand(uuid?: string) {
        if (uuid) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.callExternalControlData(uuid);
          $q.notify({
            color: "positive",
            icon: "done",
            message: $t.t("send command") + $t.t("success") + "!",
            position: "top",
            timeout: 1500,
          });
        }
      },
      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");
          }
        }
      },
    };
  },
});
</script>
