<template>
  <v-dialog v-model="showDialog" v-show="room" class="ma-0 pa-0" :width="$vuetify.breakpoint.smAndUp ? '688px' : '95%'">
    <div class="dialog-content text-center">
      <template>
        <v-icon color="black" size="30">poll</v-icon>
        <h2 class="dialog-title">
          {{ $t("poll_create.title") }}
        </h2>
        <div class="dialog-text">{{ $t("poll_create.intro") }}</div>
      </template>
      <v-form v-model="isValid" ref="pollcreateform">
        <v-container fluid class="poll-create-dialog-content">
          <v-row cols="12">
            <v-col cols="12">
              <v-switch
                v-model="pollIsDisclosed"
                inset
                :label="pollIsDisclosed ? $t('poll_create.poll_disclosed') : $t('poll_create.poll_undisclosed')"
              ></v-switch>
            </v-col>
          </v-row>
          <v-row cols="12">
            <v-col cols="12">
              <v-text-field
                outlined
                :disabled="isCreating"
                v-model="pollQuestion"
                :label="$t('poll_create.question_label')"
                :rules="[(v) => !!v || $t('poll_create.question_required')]"
              ></v-text-field>
            </v-col>
          </v-row>

          <v-row v-for="(answer, index) in pollAnswers" cols="12" :key="answer.id">
            <v-col cols="12">
              <v-text-field
                outlined
                :disabled="isCreating"
                v-model="answer.text"
                :label="$t('poll_create.answer_label', { index: index + 1 })"
                :append-icon="pollAnswers.length > 1 ? 'delete' : null"
                @click:append="removeAnswer(index)"
                :rules="[(v) => !!v || $t('poll_create.answer_required')]"
              ></v-text-field>
            </v-col>
          </v-row>

          <v-row
            ><v-col
              ><v-btn @click.stop="addAnswer">{{ $t("poll_create.add_answer") }}</v-btn></v-col
            ></v-row
          >
        </v-container>
      </v-form>
      <div class="poll-create-status">
        {{ status }}
        <v-progress-circular v-if="isCreating" indeterminate color="primary" size="14"></v-progress-circular>
      </div>
      <v-container fluid>
        <v-row cols="12">
          <v-col cols="6">
            <v-btn
              id="btn-create-poll-cancel"
              depressed
              text
              block
              class="text-button"
              @click="showDialog = false"
              :disabled="isCreating"
              >{{ $t("menu.cancel") }}</v-btn
            >
          </v-col>
          <v-col cols="6" align="center">
            <v-btn
              id="btn-create-poll"
              color="red"
              depressed
              block
              class="filled-button"
              @click.stop="onCreatePoll()"
              :disabled="isCreating"
              >{{ $t("poll_create.create") }}</v-btn
            >
          </v-col>
        </v-row>
      </v-container>
    </div>
  </v-dialog>
</template>
<script>
import roomInfoMixin from "./roomInfoMixin";
import util from "../plugins/utils";

export default {
  name: "CreatePollDialog",
  mixins: [roomInfoMixin],
  props: {
    show: {
      type: Boolean,
      default: function() {
        return false;
      },
    },
  },
  data() {
    return this.defaultData();
  },
  watch: {
    show: {
      handler(newVal, ignoredOldVal) {
        this.showDialog = newVal;
      },
    },
    showDialog() {
      if (!this.showDialog) {
        this.$emit("close");
      } else {
        // Reset values
        let defaults = this.defaultData();
        this.isValid = defaults.isValid;
        this.isCreating = defaults.isCreating;
        this.status = defaults.status;
        this.pollIsDisclosed = defaults.pollIsDisclosed;
        this.pollQuestion = defaults.pollQuestion;
        this.pollAnswers = defaults.pollAnswers;
        this.autoIncrementId = defaults.autoIncrementId;
        if (this.$refs.pollcreateform) {
          this.$refs.pollcreateform.resetValidation();
        }
      }
    },
  },

  methods: {
    defaultData() {
      return {
        showDialog: false,
        isValid: true,
        isCreating: false,
        status: String.fromCharCode(160),
        pollIsDisclosed: true,
        pollQuestion: "",
        pollAnswers: [
          { id: "1", text: "" },
          { id: "2", text: "" },
        ],
        autoIncrementId: 2,
      };
    },
    addAnswer() {
      if (this.pollAnswers.length < 20) {
        // MAX length according to spec
        this.autoIncrementId += 1;
        this.pollAnswers.push({ id: "" + this.autoIncrementId, text: "" });
      }
    },
    removeAnswer(index) {
      this.pollAnswers.splice(index, 1);
    },
    onCreatePoll() {
      if (this.$refs.pollcreateform.validate()) {
        this.isCreating = true;
        this.status = this.$t("poll_create.creating");
        util
          .createPoll(
            this.$matrix.matrixClient,
            this.room.roomId,
            this.pollQuestion,
            this.pollAnswers,
            this.pollIsDisclosed
          )
          .then(() => {
            console.log("Sent message");
            this.isCreating = false;
            this.showDialog = false;
          })
          .catch((err) => {
            console.log("Failed to send:", err);
            this.isCreating = false;
            this.status = this.$t("poll_create.failed");
          });

        setTimeout(() => {}, 3000);
      } else {
        this.isValid = false;
      }
    },
  },
};
</script>

<style lang="scss">
@import "@/assets/css/chat.scss";
@import "@/assets/css/components/poll.scss";
</style>
