<template>
  <div>
    <div class="onboarding intro" v-if="!showForm && !FailedGoogleCreds">
      <div class="inner-wrap text-center">
        <template>
          <img
            :src="logo_path+'Logo.svg'"
            id="logo"
            class="onboarding-logo"
          />
          <h3 class="text-center">Welcome to Enstract, {{ name }}</h3>
          <p class="text-center tag">Lets get you setup!</p>
          <a
            class="enstract-button eb-medium margin-left-auto text-center"
            @click="showForm = !showForm"
            >Get Started</a
          >
        </template>
      </div>
    </div>

    <div class="onboarding steps" ref="container" v-if="showForm">
      <div class="inner-wrap">
        <template>
          <div class="text-center">
            <img
              :src="logo_path+'Logo.svg'"
              id="logo"
              class="onboarding-logo"
            />
          </div>

          <stepper :options="stepperOptions">
            <div slot="step-1">

            <div class="onboarding-google-intro">
               <h4 class="text-center">Do you have a Google account?</h4>
               <p class="text-center">Firstly, you’ll need a Google account in order to use this plugin. Don’t worry if you don’t have one yet, we’ll take you to where you can set one up - for free.</p>
            </div>

             <div class="row onboarding-accounts">
               <div class="onboarding-1of3">
                 <i class="fal fa-times-square"></i>
                 <p class="text-center">I don’t have a Google account yet. I need to create one.</p>
                  <Ancor :AncorClass="'enstract-button eb-large margin-left-auto text-center'" 
                  :link="'https://accounts.google.com/signup/v2/webcreateaccount'" :name="'Create Account'"></Ancor>
               </div>
               <div class="onboarding-divider">
                 <p class="m-only">Or</p>
                 <img :src="logo_path+'divider.svg'" alt="">
               </div>
               <div class="onboarding-1of3">
                 <i class="fal fa-check-square"></i>
                 <p class="text-center">All set! I’ve already got a Google account ready & waiting to go.</p>
                  <Ancor @click.native="letsGo" :AncorClass="'enstract-button eb-large margin-left-auto text-center'" 
                  :name="'Lets go!'"></Ancor>
               </div>
             </div>

            </div>

            <div slot="step-2">
              <h4>Create a project</h4>

              <p>
               Great! Now we’ve confirmed you have a Google account, we need to configure your Google Cloud Console in order for us to extract the entities within the content of your website.
              </p>

              <p>To do this, we need to create a project.</p>

              <p>
                In the Cloud Console, on the project selector page, click the “Create Project” button as below. This should be situated in the upper right corner of the screen.
              </p>

              <div class="onboarding-screenshots">
                <img :src="logo_path+'Step-1.png'" width="200" height="200" />
              </div>

              <Ancor :AncorClass="'enstract-button eb-large margin-left-auto text-center'" 
                  :link="'https://console.cloud.google.com/projectselector2/home/dashboard?_ga=2.265759880.600261004.1604583111-595398001.1599767518'" :name="'Go to the project selector page'"></Ancor>
            </div>

            <div slot="step-3">
              <h4>Enable Billing</h4>
              <p>
                Next, we need to ensure billing is enabled for this project. Please dont be concerned. The billing section is for Google Cloud, not Enstract. If you keep your usage below 5,000* units you will not be charged anything by Google. 
              </p>

              <p>
                * For more infomation, please see <a href="https://cloud.google.com/natural-language/pricing" target="_blank">Google's pricing.</a>
              </p>

              <p>To create your Billing account simply click the button below, follow the instructions and then return here to continue with your setup.</p>

                <Ancor :AncorClass="'enstract-button eb-medium margin-left-auto text-center'" 
                  :link="'https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project.'" :name="'Enable Billing'"></Ancor>
            </div>

            <div slot="step-4">
              <h4>Enable the API</h4>
              <p>
                Nearly there! You’re doing grand. Next we need to enable the Cloud Natural Language API for the Entity extraction functionality to work.
              </p>

              <Ancor :AncorClass="'enstract-button eb-medium margin-left-auto text-center'" 
                  :link="'https://console.cloud.google.com/flows/enableapi?apiid=language.googleapis.com&_ga=2.196034731.600261004.1604583111-595398001.1599767518'" :name="'Enable the API'"></Ancor>
            </div>

            <div slot="step-5">
              <h4>Create & Download your Private Key</h4>
              <p>Setup authentication:</p>
              <ol>
                <li>
                  <p>
                    In the Cloud Console, go to the <b>Create service account key</b> page.
                  </p>
                  <p>

                 <Ancor :AncorClass="'enstract-button eb-large text-center'" 
                  PosClass="text-left"
                  :link="'https://console.cloud.google.com/apis/credentials/serviceaccountkey?_ga=2.194068906.600261004.1604583111-595398001.1599767518'" :name="'Create service account key'"></Ancor>
                  </p>
                </li>
                <li>
                  <p>
                    From the <b>Service account</b> list. select
                    <b>New service account.</b>
                  </p>
                </li>
                <li>
                  <p>In the <b>Service account name</b> field, enter a name. Eg: "Enstract SEO Plugin"</p>
                </li>
                <li>
                  <p>
                    From the <b>Role</b> list, select <b>Project > Owner.</b>
                  </p>
                  <p class="note-warning">
                    <b>Note:</b>
                    The Role field affects which resources your service account can access in your project. You can revoke these roles or grant additional roles later. We do not recommend granting the Owner, Editor, or Viewer roles.
                  </p>
                </li>

                <li>
                  <p>
                    Click <b>Create.</b> A small JSON file that contains your key will be downloaded onto your computer.
                  </p>
                </li>
              </ol>
            </div>

            <div slot="step-6">
              <h4>Upload your Private Key</h4>
              <p>
                You’re almost there - the end is in sight! The final step in this process is for you to securely provide a copy of your Private Key to us to complete the connection with your account. 
              </p>

              <p>
                You can rest assured that your key is safe with us. We don’t store the file itself anywhere on our servers, we extract the contents and encrypt it in our database.
              </p>

              <div class="input-group mb-3 upload-key-group">
                <div class="input-group-prepend">
                  <span
                    class="input-group-text register__icon"
                    id="basic-addon1"
                    ><i class="far fa-file-code"></i></span>
                </div>
                <input
                  type="file"
                  class="form-control"
                  ref="file"
                  style="display: none"
                  @change="onFileChange"
                />

                <input
                  type="text"
                  v-model="tmp_file"
                  class="form-control"
                  readonly="readonly"
                  placeholder="Private Key"
                  @click="$refs.file.click()"
                  required="required"
                />

                <button
                  class="eb-small text-center white-color upload-btn"
                  @click="$refs.file.click()"
                >
                  Upload
                </button>
              </div>
              <br />

              <Ancor @click.native="userOnBoarding" :AncorClass="'enstract-button eb-medium margin-left-auto text-center'" 
                  :name="'Finish'"></Ancor>

              <div v-if="errors" class="errors text-center">
                <template v-for="error in errors">
                  <p>{{ error }}</p>
                </template>
              </div>
            </div>

            <div slot="step-7">
              <div v-if="CheckingGoogle" class="text-center">
                <h4>Finishing up...</h4>
                <p>We are just checking your credentials with google</p>
                <img
                  :src="logo_path+'spinner.gif'"
                  id="logo"
                />
              </div>

              <div
                v-if="!CheckingGoogle && !FailedGoogleCreds && !resetFormFlag"
                class="text-center"
              >
                <span class="thumbs-up-icon"
                  ><i class="far fa-thumbs-up"></i
                ></span>
                <h4>You're done!</h4>
                <p>
                  That's it - you're all setup & ready to go! Before you get started however, we recommend setting up a budget in your Google account. Here’s how you can do that.
                </p>

                <p>
                  <a class="enstract-button eb-medium margin-left-auto text-center budget-btn" href="https://cloud.google.com/billing/docs/how-to/budgets#create-budget" target="_blank">Set up Budgets</a>
                </p>

                <br clear="both" />

                <a
                  @click="startEnstract"
                  class="enstract-button start-enstract eb-large margin-left-auto text-center"
                  >Start using Enstract</a
                >
              </div>

              <div v-if="FailedGoogleCreds">
                <h4 class="text-center">Opps, something went wrong</h4>
                <p class="text-center">
                  It appears your google credentials don't appear to be correct.
                  Click go back to double check your credentials.
                </p>

                <a
                  @click="resetForm"
                  class="enstract-button eb-medium margin-left-auto text-center"
                  >Go back</a
                >
              </div>
            </div>
          </stepper>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import Stepper from "./Stepper/Stepper.vue";
import Ancor from "../includes/Ancor.vue";
import api from "../../mixins/api";

export default {
  mixins: [api],
  components: {
    Stepper,
    Ancor
  },
  data() {
    return {
      project_id: "",
      google_json: "",
      isSubmitted: false,
      logo_path: "",
      showForm: false,
      tmp_file: "",
      CheckingGoogle: false,
      FailedGoogleCreds: false,
      resetFormFlag: false,
      errors: [],
      stepperOptions: {
        headers: [
          {title: "", stepName: ""},
          { title: "", stepName: "" },
          { title: "" },
          { title: "" },
          { title: "" },
          { title: "" },
          { title: "" },
        ],
        prevText: "Previous",
        nextText: "Next",
      },
    };
  },
  mounted() {
    this.logo_path = wpApiSettings.assets_url;
    document.body.classList.add("onboarding-body");
  },
  methods: {
    async userOnBoarding() {
      if (this.google_json.length == 0) {
        this.errors.push("The private key is reqiured");
      } else {
        this.errors = [];

        this.isSubmitted = true;
        this.CheckingGoogle = true;
        document.getElementById("next-button").click();
        document.getElementById("foot").style.display = "none";

        let formData = new FormData();

        formData.append("project_id", this.project_id);
        formData.append("google_json", this.google_json);
        formData.append("site_url", wpApiSettings.site_url);

        const response = await this.api(
          "post",
          window.apipath + "/users/onboarding",
          formData,
          0,
          1
         );

        if (response.status == 200) {
          this.isSubmitted = false;
          this.CheckingGoogle = false;
          this.FailedGoogleCreds = false;
          this.google_json = '';
          this.tmp_file = "";
          this.resetFormFlag = false;

          // Remove navigation prompt
          window.onbeforeunload = null;
        }

        var message = response.data.message;

        if(message) {
          if (message.includes("403") == true) {
            this.isSubmitted = false;
            this.CheckingGoogle = false;
            this.FailedGoogleCreds = true;
          }
        }

        if (response.status == 422) {
          this.isSubmitted = false;
        }
      }
    },
    startEnstract() {
      // Remove navigation prompt
      window.onbeforeunload = null;
      this.showForm = false;
      this.$router.push({ name: "dashboard.settings" }).catch(() => {});
    },
    resetForm() {
      this.showForm = true;
      this.FailedGoogleCreds = false;
      this.resetFormFlag = true;
      document.getElementById("foot").style.display = "flex";
      document.getElementById("prev-button").click();
    },
    onFileChange(e) {
      this.google_json = this.$refs.file.files[0];
      this.tmp_file = e.target.files[0].name;
        window.onbeforeunload = function(){
          return 'Are you sure you want to leave? you have unsaved progress';
        };
    },
    letsGo() {
      document.getElementById("next-button").click();
    },
  },
  destroyed() {
    document.body.classList.remove("onboarding-body");
  },
  props: ["name", "OnBoardingComplete"],
};
</script>
