<template>
  <div>
    <main v-if="boolLoaded" id="main" style="margin-top:20px; padding-bottom:50px;">
      <div class="container">
        <div class="row">
          <div class="col">
            <div class="section-header">
              <h2>Upload Campaign</h2>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <!--UPLOAD-->
            <h2 class="mb-5">New Campaign</h2>
            <form enctype="multipart/form-data" novalidate v-if="isInitial || isSaving">
              <div>
                <input
                  type="file"
                  multiple
                  :name="uploadFieldName"
                  :disabled="isSaving"
                  @change="
                    filesChange($event.target.files);
                    fileCount = $event.target.files.length;
                  "
                />
                <p v-if="isSaving">Uploading {{ fileCount }} files...</p>
              </div>
            </form>
            <div>
              <alert v-if="isSuccess" :text="errorMessage" :type="errorOccurred" />
              <button v-if="isSuccess" class="btn-solid-blue" @click="openInNewTab">
                View
              </button>
              <alert v-if="isFailed" :text="errorMessage" :type="errorOccurred" />
            </div>
          </div>
        </div>
        <hr class="mt-5" />
        <div class="row mt-5">
          <div class="col">
            <h2>Uploaded Campaigns</h2>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <ListView
              :items="uploadedCampaigns"
              :search="false"
              @onDelete="Delete"
              :deleteable="true"
            />
          </div>
        </div>
      </div>
    </main>

    <div v-else id="preloader"></div>
  </div>
</template>

<script>
/* eslint-disable */
import { mapActions, mapState } from "vuex";
import Alert from "../shared/alert";
import ListView from "../shared/listView";

const STATUS_INITIAL = 0,
  STATUS_SAVING = 1,
  STATUS_SUCCESS = 2,
  STATUS_FAILED = 3;

export default {
  name: "app",
  components: {
    Alert,
    ListView
  },
  data() {
    return {
      uploadedFiles: [],
      errorOccurred: "",
      errorMessage: "",
      uploadError: null,
      currentStatus: null,
      uploadFieldName: "photos",
      fileCount: 0,
      files: new FormData(),
      link: "",
      boolLoaded: false
    };
  },
  computed: {
    ...mapState("campaign", ["uploadedCampaigns"]),
    isInitial() {
      return this.currentStatus === STATUS_INITIAL;
    },
    isSaving() {
      return this.currentStatus === STATUS_SAVING;
    },
    isSuccess() {
      return this.currentStatus === STATUS_SUCCESS;
    },
    isFailed() {
      return this.currentStatus === STATUS_FAILED;
    }
  },
  methods: {
    ...mapActions("campaign", ["uploadCampaign", "getUploadedCampaign", "deleteUploadedCampaign"]),
    openInNewTab() {
      window.open(this.link, "_blank");
    },
    reset() {
      // reset form to initial state
      this.currentStatus = STATUS_INITIAL;
      this.uploadedFiles = [];
      this.uploadError = null;
    },
    Delete(item) {
      this.deleteUploadedCampaign(item.id);
    },
    save() {
      // upload data to the server
      this.currentStatus = STATUS_SAVING;
      const files = this.files;
      this.boolLoaded = false;
      this.uploadCampaign(files)
        .then(data => {
          console.log(data);
          setTimeout(() => {
            this.link = data.link;
            this.currentStatus = STATUS_SUCCESS;
            this.errorOccurred = "SUCCESS";
            this.errorMessage = "Done! Please click View below to view the campaign " + data.link;
            this.getUploadedCampaign().then(() => {
              this.boolLoaded = true;
            });
          }, 100);
        })
        .catch(ex => {
          console.log(ex);
          this.currentStatus = STATUS_FAILED;
          this.errorOccurred = "ERROR";
          this.errorMessage = "Error!";
        });

      //   upload(formData)
      //     .then(x => {
      //       this.uploadedFiles = [].concat(x);
      //       this.currentStatus = STATUS_SUCCESS;
      //     })
      //     .catch(err => {
      //       this.uploadError = err.response;
      //       this.currentStatus = STATUS_FAILED;
      //     });
    },
    filesChange(fileList) {
      this.files.append("file", fileList[0], fileList[0].name);
      this.save();
    }
  },
  mounted() {
    this.reset();
    this.getUploadedCampaign().then(() => {
      this.boolLoaded = true;
    });
  }
};
</script>

<style lang="scss" scoped>
.dropbox {
  outline: 2px dashed grey; /* the dash box */
  outline-offset: -10px;
  background: lightcyan;
  color: dimgray;
  padding: 10px 10px;
  min-height: 200px; /* minimum height */
  position: relative;
  cursor: pointer;
}

.input-file {
  opacity: 0; /* invisible but it's there! */
  width: 100%;
  height: 200px;
  position: absolute;
  cursor: pointer;
}

.dropbox:hover {
  background: lightblue; /* when mouse over to the drop zone, change color */
}

.dropbox p {
  font-size: 1.2em;
  text-align: center;
  padding: 50px 0;
}
</style>
