import useChannelsTabWazzupExtensionStore from "./../../store/useChannelsTabWazzupExtensionStore.js";
import {
  WhatsappChannel,
  WapiChannel,
  InstagramChannel,
  TelegramChannel,
  TelegramBotChannel,
  AvitoChannel,
  VKChannel,
} from "./EditSelectedOption.js";

export const EditChannel = {
  name: "edit-channel",
  emits: ["setSelected"],

  components: {
    "whatsapp-channel-edit-mode": WhatsappChannel,
    "wapi-channel-edit-mode": WapiChannel,
    "instagram-channel-edit-mode": InstagramChannel,
    "telegram-channel-edit-mode": TelegramChannel,
    "telegram-bot-channel-edit-mode": TelegramBotChannel,
    "avito-channel-edit-mode": AvitoChannel,
    "vkontakte-channel-edit-mode": VKChannel,
  },

  props: {
    channelId: { type: String, default: "" },
    selected: { type: String, default: "" },
    transport: { type: String, default: "" },
  },

  setup(props, { emit }) {
    const { t } = VueI18n.useI18n();
    const channelStore = useChannelsTabWazzupExtensionStore();
    const metaTables = Vue.inject("metaTables");
    const сreateNewEntry = Vue.ref("");

    Vue.onMounted(() => {
      checkHelpButtonsOnCurrentPage();
      bind_help_bt("wazzup");
    });

    function genid() {
      let dt = new Date().getTime();
      let mask = "ixxxyxxx"; //'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
      return mask.replace(/[xy]/g, function (c) {
        let r = (dt + Math.random() * 16) % 16 | 0;
        dt = Math.floor(dt / 16);
        return (c == "x" ? r : (r & 0x3) | 0x8).toString(36);
      });
    }

    return {
      channelStore,
      сreateNewEntry,

      addTable() {
        let id = genid();
        channelStore.channels[props.channelId]["additional_option"] = [
          ...channelStore.channels[props.channelId]["additional_option"],
          {
            id,
            table_id: 0,
            phone_field_id: 0,
            username_field_id: 0,
            deleted: false,
            priority: "low",
            filter: 0,
          },
        ];
        emit("setSelected", id);
      },

      getTableName(id) {
        if (id == 0) {
          return t("no_name");
        }

        let tableName = "";
        Object.keys(metaTables).forEach((i) => {
          if (metaTables[i].id == id) {
            tableName = metaTables[i].name || "";
          }
        });
        return tableName;
      },

      deleteTable(id) {
        channelStore.channels[props.channelId]["additional_option"].forEach(
          (el) => {
            if (el.id == id) {
              el.deleted = true;
            }
          }
        );
        emit("setSelected", "");
      },

      getAllSelectedTable() {
        let arr = [];
        let channel =
          channelStore.channels[props.channelId]["additional_option"];
        channel.forEach((el) => {
          if (el.table_id > 0) {
            let tableName = metaTables[el.table_id].name;
            arr.push({
              id: el.table_id,
              name: tableName,
            });
          }
        });
        return arr;
      },
    };
  },

  template: /*html*/ `
    <div class="wazzup__channel_item">
      <table>
        <tr>
          <td colspan="2"><span>{{ $t('channel_id') }} :</span></td>
          <td
            style="text-align:left; padding: 6px 4px 3px 5px;"
          >{{ channelId }}</td>
        </tr>

        <tr>
          <td><span>{{ $t('channel_name') }}</span></td>
          <td>
            <span h_id="wazzup_channel_name" class="help_bt"></span>
            <span>:</span>
          </td>
          <td>
            <input
              type="text"
              class="form-control"
              v-model="channelStore.channels[this.channelId]['channel_name']"
            />
          </td>
        </tr>

        <tr>
          <td><span>{{ $t('create_new_entry') }}</span></td>
          <td>
            <span h_id="wazzup_create_new_entry" class="help_bt"></span>
            <span>:</span>
          </td>
          <td>
            <select
              class="form-control"
              v-model="channelStore.channels[this.channelId]['create_new_entry']"
            >
              <option value="0"></option>
              <template v-for="table in getAllSelectedTable()">
                <option :value="table.id">{{ table.name }}</option>
              </template>
            </select>
          </td>
        </tr>
      </table>
    </div>

    <div class="wazzup__channels_list" style="margin-top: 20px;">
      <template
        v-for="item in channelStore.channels[this.channelId]['additional_option']"
        :key="id"
      >
        <div class="wazzup__channels_list__item">
          <delete-icon
            :styles="{cursor:'pointer'}"
            @handle="deleteTable(item.id)"
          ></delete-icon>

          <span
            v-if="item.deleted"
            style="font-size: 16px; text-decoration: line-through; color: #bbb;"
          >{{ getTableName(item.table_id) }}</span>
          <a
            v-else
            style="cursor:pointer; font-size:16px; text-decoration: underline dotted;"
            @click="$emit('setSelected', item.id)"
          >{{ getTableName(item.table_id) }}</a>
        </div>
      </template>

      <div class="wazzup__channels_list__item">
        <a
          style="cursor:pointer; font-size:16px; text-decoration: underline dotted;"
          @click="addTable"
        >{{ $t('add_table') }}</a>
      </div>
    </div>

    <template v-if="selected != ''">
      <whatsapp-channel-edit-mode
        v-if="transport == 'whatsapp'"
        :selected="selected"
        :channelId="channelId"
      ></whatsapp-channel-edit-mode>

      <wapi-channel-edit-mode
        v-if="transport == 'wapi'"
        :selected="selected"
        :channelId="channelId"
      ></wapi-channel-edit-mode>

      <instagram-channel-edit-mode
        v-if="transport == 'instagram'"
        :selected="selected"
        :channelId="channelId"
      ></instagram-channel-edit-mode>

      <telegram-channel-edit-mode
        v-if="transport == 'tgapi'"
        :selected="selected"
        :channelId="channelId"
      ></telegram-channel-edit-mode>

      <telegram-bot-channel-edit-mode
        v-if="transport == 'telegram'"
        :selected="selected"
        :channelId="channelId"
      ></telegram-bot-channel-edit-mode>

      <avito-channel-edit-mode
        v-if="transport == 'avito'"
        :selected="selected"
        :channelId="channelId"
      ></avito-channel-edit-mode>

      <vkontakte-channel-edit-mode
        v-if="transport == 'vk'"
        :selected="selected"
        :channelId="channelId"
      ></vkontakte-channel-edit-mode>
    </template>
  `,
};
