<template>
  <div
    class="row full-width"
    style="height: 35vh"
    @touchstart="$event.stopPropagation()"
    v-show="$store.state.power_state"
  >
    <div :class="'col-' + ($store.state.landspace ? '9' : '8')">
      <div class="q-ma-md bg-primary">
        <div class="row bg-primary">
          <q-tabs
            v-model="tab"
            dense
            inline-label
            class="col-12 text-white bg-accent"
            style="border: none"
            active-color="secondary"
            indicator-color="secondary"
            active-bg-color="primary"
            align="justify"
          >
            <q-tab
              name="signal_source"
              no-caps
              icon="img:pad/signal_source_tab_icon.png"
              :label="$t('signal source')"
            />
            <q-separator dark vertical inset />

            <q-tab
              name="singal_polling"
              no-caps
              icon="img:pad/polling_tab_icon.png"
              :label="$t('signal polling')"
            />
            <q-separator dark vertical inset />

            <q-tab
              name="mode"
              no-caps
              icon="img:pad/mode_tab_icon.png"
              :label="$t('mode')"
            />
            <q-separator dark vertical inset />

            <q-tab
              name="plan"
              no-caps
              icon="img:pad/plan_tab_icon.png"
              :label="$t('plan')"
            />
          </q-tabs>
        </div>
        <q-separator />

        <q-tab-panels v-model="tab" animated class="fit text-black">
          <q-tab-panel
            name="signal_source"
            class="full-width __panel_item q-pa-xs"
          >
            <q-scroll-area class="fit q-pr-md">
              <draggable
                class="row q-px-md"
                v-model="signal_sources"
                group="signal_source"
                item-key="uuid"
                :move="() => false"
                @drop="onSignalSourceDrop($event)"
              >
                <template #item="{ element }">
                  <div class="col-4 q-pr-sm q-pb-sm">
                    <q-btn
                      class="col-row fit overflow-hidden bg-accent text-white"
                      :icon="getItemIcon(element.window_type)"
                    >
                      <span class="col q-ml-md text-left">
                        {{ element.name }}
                      </span>
                    </q-btn>
                  </div>
                </template>
              </draggable>
            </q-scroll-area>
          </q-tab-panel>
          <q-tab-panel
            name="singal_polling"
            class="full-width __panel_item q-pa-xs"
          >
            <q-scroll-area class="fit q-pr-md">
              <draggable
                class="row q-px-md"
                v-model="pollings"
                group="polling"
                item-key="uuid"
                :move="() => false"
                @drop="onPollingDrop($event)"
              >
                <template #item="{ element }">
                  <div class="col-4 q-pr-sm q-pb-sm">
                    <q-btn
                      class="col-row fit overflow-hidden bg-accent text-white"
                      icon="img:pad/polling_icon.png"
                    >
                      <span class="col q-ml-md text-left">
                        {{ element.name }}
                      </span>
                    </q-btn>
                  </div>
                </template>
              </draggable>
            </q-scroll-area>
          </q-tab-panel>

          <q-tab-panel name="mode" class="full-width __panel_item q-pa-xs">
            <q-scroll-area class="fit q-pr-md">
              <draggable
                class="row q-px-md"
                v-model="modes"
                group="mode"
                item-key="uuid"
                :move="() => false"
                @drop="onModeDrop($event)"
              >
                <template #item="{ element }">
                  <div class="col-4 q-pr-sm q-pb-sm">
                    <q-btn
                      class="col-row fit overflow-hidden bg-accent text-white"
                      icon="img:pad/mode_icon.png"
                    >
                      <span class="col q-ml-md text-left">
                        {{ element.name }}
                      </span>
                    </q-btn>
                  </div>
                </template>
              </draggable>
            </q-scroll-area>
          </q-tab-panel>
          <q-tab-panel name="plan" class="full-width __panel_item q-pa-xs">
            <q-scroll-area class="fit q-pr-md">
              <draggable
                class="row q-px-md"
                v-model="plans"
                group="plans"
                item-key="uuid"
                :move="() => false"
                @drop="onPlanDrop($event)"
              >
                <template #item="{ element }">
                  <div class="col-4 q-pr-sm q-pb-sm">
                    <q-btn
                      class="col-row fit overflow-hidden bg-accent text-white"
                      icon="img:pad/plan_icon.png"
                    >
                      <span class="col q-ml-md text-left">
                        {{ element.name }}
                      </span>
                    </q-btn>
                  </div>
                </template>
              </draggable>
            </q-scroll-area>
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </div>

    <div
      class="full-height"
      :class="'col-' + ($store.state.landspace ? '3' : '4')"
    >
      <div>
        <div
          v-if="$q.platform.is.ios"
          class="row q-my-lg"
          style="width: 1px; height: 1px"
        ></div>
        <div class="row q-my-md" style="width: 1px; height: 1px"></div>
        <div class="row">
          <q-space />
          <q-btn
            :disable="!can_next_prev_window || plan_running"
            icon="img:pad/play_control/play_prev_icon.png"
            flat
            size="1.2rem"
            class="col-auto"
            @click="playPrev($event)"
          />
          <q-btn
            :disable="!can_pause_window || plan_running"
            :icon="
              selected_window?.paused
                ? 'img:pad/play_control/play_icon.png'
                : 'img:pad/play_control/pause_icon.png'
            "
            flat
            size="2.4rem"
            class="col-auto"
            @click="selected_window?.paused ? play($event) : pause($event)"
          />
          <q-btn
            :disable="!can_next_prev_window || plan_running"
            icon="img:pad/play_control/play_next_icon.png"
            flat
            size="1.2rem"
            class="col-auto"
            @click="playNext($event)"
          />
          <q-space />
        </div>
        <div class="row q-my-sm">
          <q-space />
          <q-btn
            :disable="plan_running"
            icon="img:pad/play_control/volume_down_icon.png"
            flat
            size="1.2rem"
            class="col-auto"
            @click="volumeDown($event)"
          />
          <q-btn
            :disable="plan_running"
            :icon="
              selected_window?.muted
                ? 'img:pad/play_control/mute_icon.png'
                : 'img:pad/play_control/unmute_icon.png'
            "
            flat
            size="1.2rem"
            class="col-auto"
            @click="
              selected_window?.muted ? unmuteWindow($event) : muteWindow($event)
            "
          />
          <q-btn
            :disable="plan_running"
            icon="img:pad/play_control/volume_up_icon.png"
            flat
            size="1.2rem"
            class="col-auto"
            @click="volumeUp($event)"
          />
          <q-space />
        </div>
      </div>
    </div>
    <q-space />
  </div>
</template>

<style scoped>
.__panel_item {
  height: 27vh;
}
</style>

<script lang="ts">
import { defineComponent, Ref, ref, computed, watch } from "vue";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { useStore } from "src/store";
import draggable from "src/third_lib/vuedraggable/vuedraggable";
import { SignalSourceEntity } from "src/entities/SignalSourceEntity";
import { Common } from "src/common/Common";
import EventBus, { EventNamesDefine } from "src/common/EventBus";
import GlobalData from "src/common/GlobalData";
import { WindowOpenNotifyEntity } from "src/entities/MultimediaWindowEntity";

export default defineComponent({
  name: "PadBottomBarPage",
  components: { draggable },
  setup() {
    const $store = useStore();
    const $q = useQuasar();
    const $t = useI18n();

    const signal_sources = computed({
      get: () =>
        $store.state.signal_sources.filter(
          (element) => element && !element.local_file_flag
        ),
      set: (val) => null,
    });

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

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

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

    const tab = ref("signal_source");

    let selected_window: Ref<WindowOpenNotifyEntity | null> = ref(null);
    let is_multimedia_window = ref(false);

    let can_pause_window = ref(false);
    let can_next_prev_window = ref(false);

    const plan_running = computed(
      () => $store.state.current_running_plan.trim() != ""
    );

    watch(
      () => $store.state.selected_window,
      (newValue, oldValue) => {
        const window = $store.state.windows.find(
          (element) => element && element.uuid == newValue
        );
        if (window) {
          selected_window.value = window;
          const signal_source = GlobalData.getInstance().signal_source.find(
            (element) =>
              element && element.uuid == window.signal_source_table_uuid
          );
          if (signal_source) {
            const type = window.polling
              ? window.polling_window_type
              : signal_source.window_type;
            is_multimedia_window.value =
              type == "EwindowType::Multimedia" ||
              type == "EwindowType::Rtsp" ||
              type == "EwindowType::HdmiIn";

            can_pause_window.value =
              type == "EwindowType::Multimedia" ||
              type == "EwindowType::HdmiIn";
            can_next_prev_window.value = type == "EwindowType::Multimedia";
          }
        } else {
          selected_window.value = null;
          is_multimedia_window.value = false;
          can_pause_window.value = false;
          can_next_prev_window.value = false;
        }
      }
    );

    const emit_drop_events = (evt: any, type: string) => {
      if (
        evt.data &&
        evt.event &&
        evt.event.changedTouches &&
        evt.event.changedTouches.length
      ) {
        const touchX = evt.event.changedTouches[0].pageX;
        const touchY = evt.event.changedTouches[0].pageY;
        EventBus.getInstance().emit(EventNamesDefine.DropToWall, {
          type,
          data: evt.data,
          pos: {
            x: touchX,
            y: touchY,
          },
        });
      }
    };

    return {
      tab,
      signal_sources,
      modes,
      pollings,
      plans,
      selected_window,
      is_multimedia_window,
      can_pause_window,
      can_next_prev_window,
      plan_running,
      loga(a: any) {
        console.log(a);
      },
      getItemIcon(item_type: string) {
        let icon_map = new Map([
          ["EwindowType::Normal", "img:pad/source_icon/media.png"],
          ["EwindowType::Multimedia", "img:pad/source_icon/media.png"],
          ["EwindowType::Web", "img:pad/source_icon/web.png"],
          ["EwindowType::Image", "img:pad/source_icon/image.png"],
          ["EwindowType::Pdf", "img:pad/source_icon/pdf.png"],
          ["EwindowType::Ppt", "img:pad/source_icon/ppt.png"],
          ["EwindowType::Rtsp", "img:pad/source_icon/rtsp.png"],
          ["EwindowType::Subtitles", "img:pad/source_icon/subtitles.png"],
          ["EwindowType::Clock", "img:pad/source_icon/clock.png"],
          ["EwindowType::Weather", "img:pad/source_icon/weather.png"],
          ["EwindowType::HdmiIn", "img:pad/source_icon/hdmi_in.png"],
          ["EwindowType::HdmiIn", "img:pad/source_icon/timer.png"],
        ]);

        if (icon_map.has(item_type)) {
          return icon_map.get(item_type);
        } else {
          return "img:pad/source_icon/media.png";
        }
      },
      onSignalSourceDrop(evt: any) {
        try {
          emit_drop_events(evt, "signal_source");
        } catch (e) {
          console.log(e);
        }
      },
      onPollingDrop(evt: any) {
        try {
          emit_drop_events(evt, "polling");
        } catch (e) {
          console.log(e);
        }
      },
      onModeDrop(evt: any) {
        try {
          emit_drop_events(evt, "mode");
        } catch (e) {
          console.log(e);
        }
      },
      onPlanDrop(evt: any) {
        try {
          emit_drop_events(evt, "plan");
        } catch (e) {
          console.log(e);
        }
      },
      volumeUp(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          let volume = selected_window.value.volume + 5;
          if (volume > 100) {
            volume = 100;
          }
          GlobalData.getInstance()
            .getCurrentClient()
            ?.setWindowVolume(selected_window.value.window_id, volume);
        }
      },
      muteWindow(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.muteWindow(selected_window.value.window_id);
        }
      },
      unmuteWindow(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.unmuteWindow(selected_window.value.window_id);
        }
      },
      volumeDown(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          let volume = selected_window.value.volume - 5;
          if (volume < 0) {
            volume = 0;
          }
          GlobalData.getInstance()
            .getCurrentClient()
            ?.setWindowVolume(selected_window.value.window_id, volume);
        }
      },
      playNext(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.windowPlayNext(selected_window.value.window_id);
        }
      },
      play(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.playWindow(selected_window.value.window_id);
        }
      },
      pause(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.pauseWindow(selected_window.value.window_id);
        }
      },
      playPrev(evt: MouseEvent) {
        evt.stopPropagation();
        if (selected_window.value) {
          GlobalData.getInstance()
            .getCurrentClient()
            ?.windowPlayPrev(selected_window.value.window_id);
        }
      },
    };
  },
});
</script>
