<template>
  <q-dialog persistent v-model="show_dialog" @before-hide="resetData">
    <q-card class="overflow-hidden" style="overflow-y: scroll; max-width: 45vw">
      <q-form @submit="onSubmit">
        <q-card-section class="q-ma-none q-pa-sm">
          <div class="row">
            <div class="col-auto text-h6">
              {{
                type == 1
                  ? $t("add signal source")
                  : type == 2
                  ? $t("edit signal source")
                  : $t("add signal source")
              }}
            </div>
            <q-space />
            <div>
              <q-btn
                :loading="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 style="max-height: 50vh; width: 45vw" class="scroll">
          <q-list>
            <q-item v-if="type != 2">
              <q-item-label>{{ $t("parent group") }}:</q-item-label>
            </q-item>
            <q-item v-if="type != 2" class="q-pa-none q-ma-none">
              <q-item-section style="padding-right: 10px">
                <q-tree
                  ref="tree"
                  class="scroll"
                  :class="loading ? 'disable_tree' : ''"
                  v-model:selected="selected"
                  :nodes="tree_nodes"
                  default-expand-all
                  node-key="uuid"
                  labelKey="name"
                  filter="group filter"
                  :filter-method="treeNodesFilter"
                >
                  <template v-slot:default-header="prop">
                    <q-item
                      class="full-width"
                      :class="
                        prop.tree.selected == prop.key ? 'item-selected-bg' : ''
                      "
                    >
                      <q-item-section avatar>
                        <q-icon
                          :name="'img:source_icon/group.png'"
                          color="orange"
                          size="28px"
                          class="q-mr-sm"
                        />
                      </q-item-section>
                      <q-item-section>
                        <div class="text-weight-bold text-primary">
                          {{ prop.node.name }}
                        </div>
                      </q-item-section>
                    </q-item>
                  </template>
                </q-tree>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-input
                  :loading="loading"
                  :disable="loading"
                  filled
                  autofocus
                  v-model="item_data.name"
                  :label="$t('signal source name')"
                  :hint="$t('please input signal source name')"
                  lazy-rules
                  :rules="[
                    (val) =>
                      (val && val.length > 0) || $t('Please type something'),
                  ]"
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                      }
                    }
                  "
                >
                  <template v-if="item_data.name" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop="item_data.name = null"
                      class="cursor-pointer"
                    />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-select
                  :loading="loading"
                  :disable="loading"
                  filled
                  option-value="value"
                  option-label="label"
                  emit-value
                  map-options
                  v-model="item_data.window_type"
                  :options="signal_source_options"
                  :label="$t('signal source type')"
                  :hint="$t('please select signal source type')"
                  @update:model-value="onSelected"
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                      }
                    }
                  "
                >
                </q-select>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section>
                <q-input
                  :loading="loading"
                  :disable="loading"
                  filled
                  @dblclick="doSelectFile"
                  v-model="item_data.media_url"
                  :label="media_url_label"
                  :hint="
                    $t('please input') +
                    media_url_label.substr(0, media_url_label.length - 2) +
                    (media_url_label.startsWith($t('file path'))
                      ? ',' + $t('dbclick select file')
                      : '')
                  "
                  lazy-rules
                  :rules="[
                    (val) =>
                      (val && val.length > 0) ||
                      $t('Please type something') +
                        ',' +
                        $t('dbclick select file'),
                  ]"
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                      }
                    }
                  "
                >
                  <template v-if="item_data.media_url" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop="item_data.media_url = null"
                      class="cursor-pointer"
                    />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
            <q-item
              v-if="item_data && item_data.window_type == 'EwindowType::Rtsp'"
            >
              <q-item-section>
                <q-input
                  :loading="loading"
                  :disable="loading"
                  filled
                  v-model="item_data.user_name"
                  :label="$t('user name')"
                  :hint="$t('please input user name')"
                  lazy-rules
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                      }
                    }
                  "
                >
                  <template v-if="item_data.user_name" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop="item_data.user_name = null"
                      class="cursor-pointer"
                    />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
            <q-item
              v-if="item_data && item_data.window_type == 'EwindowType::Rtsp'"
            >
              <q-item-section>
                <q-input
                  :loading="loading"
                  :disable="loading"
                  filled
                  v-model="item_data.password"
                  :label="$t('password')"
                  :hint="$t('please input password')"
                  lazy-rules
                  @keydown="
                    (evt) => {
                      if (evt.keyCode == 13) {
                      }
                    }
                  "
                >
                  <template v-if="item_data.password" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop="item_data.password = null"
                      class="cursor-pointer"
                    />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>

        <q-separator />

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

<style scoped>
.disable_tree {
  background: #9e9e9e;
  cursor: wait;
  pointer-events: none;
}
</style>

<script lang="ts">
import {
  defineComponent,
  ref,
  watch,
  reactive,
  onUnmounted,
  computed,
} from "vue";
import { useStore } from "src/store";
import GlobalData from "src/common/GlobalData";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import {
  SignalSourceEntity,
  SignalSourceTreeItemEntity,
} from "src/entities/SignalSourceEntity";

import FileManageDialog from "src/components/FileManageDialog.vue";
import FileEntity from "src/entities/FileEntity";

export default defineComponent({
  name: "ComponentSignalSourceDialog",
  components: { FileManageDialog },

  setup() {
    let $store = useStore();
    let $q = useQuasar();
    let $t = useI18n();

    let show_dialog = ref(false);
    let type = ref(1);
    let media_url_label = ref("URL");
    let item_data: SignalSourceEntity = reactive(new SignalSourceEntity());
    item_data.window_type = "EwindowType::Multimedia";
    const selected: any = ref(null);
    let loading = ref(false);
    let file_manage_dialog: any = ref(null);

    let suppored_window_types = new Set<string>([
      "EwindowType::Multimedia",
      "EwindowType::Web",
      "EwindowType::Image",
      "EwindowType::Rtsp",
    ]);

    let signal_source_options = [
      {
        label: $t.t("multimedia file"),
        value: "EwindowType::Multimedia",
      },
      {
        label: $t.t("Web"),
        value: "EwindowType::Web",
      },
      {
        label: $t.t("image"),
        value: "EwindowType::Image",
      },
      {
        label: $t.t("rtsp"),
        value: "EwindowType::Rtsp",
      },
    ];

    const tree_nodes = computed({
      get: () => $store.state.signal_source_tree,
      set: (val) => {},
    });

    watch(
      () => selected.value,
      (newValue, oldValue) => {
        if (newValue == null) {
          selected.value = "";
        }
      }
    );

    watch(
      () => item_data.window_type,
      (newValue, oldValue) => {
        if (!suppored_window_types.has(newValue)) {
          item_data.window_type = "EwindowType::Multimedia";
        }
      }
    );

    const setMediaUrlLabel = (value: string) => {
      switch (value) {
        case "EwindowType::Web":
          media_url_label.value = $t.t("http url") + ":";
          break;
        case "EwindowType::Rtsp":
          media_url_label.value = $t.t("RTSP url") + ":";
          break;
        default:
          media_url_label.value = $t.t("file path") + ":";
          break;
      }
    };

    const requestAddSignalSource = async () => {
      item_data.group_uuid = selected.value;
      let response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.addSignalSource(item_data);
      if (response) {
        $q.notify({
          color: response.success ? "positive" : "negative",
          icon: response.success ? "done" : "warning",
          message:
            $t.t("add signal source") +
            (response.success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
      }
    };

    const requestEditSignalSource = async () => {
      item_data.group_uuid = selected.value;

      let response = await GlobalData.getInstance()
        .getCurrentClient()
        ?.editSignalSource(item_data);
      if (response) {
        $q.notify({
          color: response.success ? "positive" : "negative",
          icon: response.success ? "done" : "warning",
          message:
            $t.t("edit signal source") +
            (response.success ? $t.t("success") : $t.t("fail")) +
            "!",
          position: "top",
          timeout: 1500,
        });
      }
    };

    return {
      show_dialog,
      type,
      signal_source_options,
      media_url_label,
      item_data,
      selected,
      loading,
      tree_nodes,
      file_manage_dialog,
      showDialog(options: any) {
        if (options) {
          type.value = options.type ?? 1;
          if (options.data && options.data.item_data) {
            SignalSourceEntity.copy(
              item_data,
              JSON.parse(JSON.stringify(options.data.item_data))
            );
          }
          if (type.value == 2) {
            selected.value = item_data.group_uuid;
          } else {
            selected.value = options.parent_node ?? "";
          }
        }
        if (item_data) {
          setMediaUrlLabel(item_data.window_type);
        }
        try {
          console.log(item_data.media_url);
          const url = new URL(item_data.media_url);
          console.log(url);
          console.log(url.host);
          console.log(url.pathname);
          if (url.host == "media" && url.pathname.startsWith("/usb")) {
            const usb_index = parseInt(url.pathname.substr("/usb".length, 1));
            if (!isNaN(usb_index)) {
              const target_path = decodeURI(url.pathname);
              item_data.media_url =
                "/usb" +
                (usb_index + 1).toString() +
                target_path.substr("/usb0".length);
            } else {
              console.error("url:", item_data.media_url);
              console.error("url:", url);
              console.error(
                "usb_index:",
                url.pathname.substr("/usb".length, 1)
              );
              console.error("usb_index:", usb_index);
            }
          } else if (
            url.host == "userdata" &&
            url.pathname.startsWith("/media_player_datas")
          ) {
            item_data.media_url = decodeURI(url.pathname).substr(
              "/media_player_datas/".length
            );
          }
        } catch {}
        show_dialog.value = true;
      },
      resetData() {
        loading.value = false;
        selected.value = null;
        SignalSourceEntity.copy(item_data);
        type.value = 1;
      },
      treeNodesFilter(node: any, filter: any) {
        return node.is_group && !node.item_data?.system_default;
      },
      onSelected(value: any) {
        setMediaUrlLabel(value as string);
      },
      async onSubmit() {
        loading.value = true;
        try {
          await (type.value == 2
            ? requestEditSignalSource()
            : requestAddSignalSource());
          show_dialog.value = false;
        } catch {}
        loading.value = false;
      },
      async doSelectFile() {
        if (!media_url_label.value.startsWith($t.t("file path"))) {
          return;
        }
        const obj = await file_manage_dialog.value.showDialogAsync("select");
        if (obj) {
          interface __I {
            path: string;
            file: FileEntity;
          }
          let { path, file }: __I = obj;
          if (path && file) {
            item_data.media_url = path + "/" + file.name;
          }
        }
      },
    };
  },
});
</script>
