<template>
  <main id="main" style="margin-top:200px; padding-bottom:50px">
    <div class="container">
      <div class="row">
        <div class="col">
          <div class="section-header">
            <h2>Reset Password</h2>
          </div>
        </div>
      </div>
      <div v-if="validLink">
        <div v-if="invalidToken">
          <div class="row mb-4">
            <div class="col">
              <alert
                :text="
                  'This link has been used previously to update your password, please request a new one'
                "
                :type="'ERROR'"
              />
            </div>
          </div>
        </div>
        <div v-else>
          <div class="row mb-4">
            <div class="col">
              <alert :text="message" :type="status" />
            </div>
          </div>
          <div class="row">
            <div class="col-md-6">
              <input
                v-model="password"
                type="password"
                class="form-control uniInput"
                placeholder="PASSWORD"
              />
            </div>
            <div class="col-md-6">
              <input
                v-model="confirmPass"
                type="password"
                class="form-control uniInput"
                placeholder="CONFIRM PASSWORD"
              />
            </div>
          </div>
          <div class="row mt-4">
            <div class="col">
              <button @click="pushToApi" class="btn-solid-blue">
                UPDATE PASSWORD
              </button>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <div class="row mb-4">
          <div class="col">
            <alert
              :text="'This link is old. Please request a new link to update your password.'"
              :type="'ERROR'"
            />
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script>
/* eslint-disable */
import axios from "axios";
import alert from "../shared/alert";

export default {
  components: {
    alert
  },
  data() {
    return {
      timeDiff: 0,
      validLink: false,
      mail: "",
      confirmPass: "",
      password: "",
      passwordType: "password",
      passwordIcon: "eye-slash",
      passwordConfirmType: "password",
      passwordConfirmIcon: "eye-slash",
      message: "",
      status: "",
      invalidToken: false
    };
  },
  created() {
    this.getTimeFromToken();
  },
  methods: {
    pushToApi() {
      if (this.password === this.confirmPass) {
        var userObj = {
          email: this.mail,
          password: this.password
        };
        axios.put("api/register/passwordUpdate", userObj).then(() => {
          this.message = "Password Updated, you can now Log in";
          this.status = "SUCCESS";
          setTimeout(() => {
            this.$router.push("/user/login");
          }, 2000);
        });
      } else {
        this.message = "Passwords do not match";
        this.status = "ERROR";
        //console.log("Passwords do not match");
      }
    },
    getTimeFromToken() {
      var decryptedBase64 = this.decrypt();
      var bytes = [];
      for (let index = 0; index < atob(decryptedBase64).length; index++) {
        var code = atob(decryptedBase64).charCodeAt(index);
        bytes = bytes.concat([code & 0xff, (code / 256) >>> 0]);
      }
      var decryptedAll = bytes.join();
      var timeArr = [];
      var mailArr = [];
      for (let i = 0; i < bytes.length; i++) {
        if (bytes[i] === 0) {
          bytes.splice(i, 1);
        }
      }

      for (let index = 0; index < bytes.length; index++) {
        if (index < 16) {
          timeArr.push(bytes[index]);
        }
      }

      for (let index = 32; index < bytes.length; index++) {
        mailArr.push(bytes[index]);
      }

      this.byteArrayToMail().then(res => {
        this.mail = res;
      });

      var Tokendate = new Date(this.byteArrayToLong(timeArr));
      var d = new Date();
      var date = new Date(d.getTime());
      var upperDate = new Date(Tokendate.setHours(Tokendate.getHours() + 1));

      if (date < upperDate) {
        this.validLink = true;
      } else {
        console.log("Link is old");
      }
    },

    async byteArrayToMail() {
      var token = await this.setToken();
      var fptokenObj = {
        token: token
      };

      //getting email from API by searching using the forgot Password token; then decription
      //of the string is not constant.
      const result = await axios.post("api/register/fptoken", fptokenObj);
      if (result.status === 200) {
        var mail = result.data.email;
        return mail;
      } else {
        this.invalidToken = true;
      }

      // for (var i = 0; i < byteArr.length; i++) {
      //   result += String.fromCharCode(parseInt(byteArr[i]))
      // }
      //return result
    },
    async setToken() {
      return this.$route.params.token;
    },
    byteArrayToLong(byteArray) {
      var length = byteArray.length;

      var result = "";
      for (var i = 0; i < length; i++) {
        result += String.fromCharCode(parseInt(byteArray[i]));
      }
      var finResult = result.replace(",", ".");

      result = parseFloat(finResult);
      return result;
    },
    decrypt() {
      const searchRegExp = /!/g;
      var actualEncryptStr = this.$route.params.token.replace(searchRegExp, "/");
      var key = "EGV~A8pn;:9&zC]6";

      //Creating the Vector Key
      var iv = this.$CryptoJS.enc.Hex.parse("e84ad660c4721ae0e84ad660c4721ae0");

      //Encoding the Password in from UTF8 to byte array
      var Pass = this.$CryptoJS.enc.Utf8.parse(key);

      //Encoding the Salt in from UTF8 to byte array
      var Salt = this.$CryptoJS.enc.Utf8.parse("insight123resultxyz");

      //Creating the key in PBKDF2 format to be used during the decryption
      var key128Bits1000Iterations = this.$CryptoJS.PBKDF2(
        Pass.toString(this.$CryptoJS.enc.Utf8),
        Salt,
        { keySize: 128 / 32, iterations: 1000 }
      );

      //Enclosing the test to be decrypted in a CipherParams object as supported by the CryptoJS libarary
      var cipherParams = this.$CryptoJS.lib.CipherParams.create({
        ciphertext: this.$CryptoJS.enc.Base64.parse(actualEncryptStr)
      });

      //Decrypting the string contained in cipherParams using the PBKDF2 key
      var decrypted = this.$CryptoJS.AES.decrypt(cipherParams, key128Bits1000Iterations, {
        mode: this.$CryptoJS.mode.CBC,
        iv: iv,
        padding: this.$CryptoJS.pad.Pkcs7
      });

      return decrypted.toString(this.$CryptoJS.enc.Utf8);
    }
  }
};
</script>

<style lang="scss" scoped></style>
