import { Component } from "@angular/core";
import { NavController, ToastController } from "ionic-angular";
import { Storage } from "@ionic/storage";

@Component({
  selector: "page-settings",
  templateUrl: "settings.html"
})
export class SettingsPage {
  keywords: string;
  privateKey: string;
  publicKey: string;

  constructor(
    public navCtrl: NavController,
    public toastCtrl: ToastController,
    private storage: Storage
  ) {
    this.loadValuesFromStorage();
  }

  async loadValuesFromStorage() {
    this.privateKey = await this.storage.get("privateKey");
    this.publicKey = await this.storage.get("publicKey");
    this.keywords = await this.storage.get("keywords");
  }

  async generateKeys() {
    const keys = await this.generateRsaKeys();

    this.publicKey = await this.extractPublicKey(keys);
    this.privateKey = await this.extractPrivateKey(keys);
  }

  save() {
    this.storage.set("publicKey", this.publicKey);
    this.storage.set("privateKey", this.privateKey);
    this.storage.set("keywords", this.keywords);

    const toast = this.toastCtrl.create({
      message: "Successfully saved!",
      position: "bottom",
      duration: 3000
    });
    toast.present();
  }

  private async generateRsaKeys() {
    return await crypto.subtle.generateKey(
      {
        name: "RSA-OAEP",
        modulusLength: 1024,
        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
        hash: { name: "SHA-256" }
      },
      true,
      ["encrypt", "decrypt"]
    );
  }

  private async extractPrivateKey(keys): Promise<string> {
    return btoa(
      String.fromCharCode.apply(
        null,
        new Uint8Array(await crypto.subtle.exportKey("pkcs8", keys.privateKey))
      )
    );
  }

  private async extractPublicKey(keys): Promise<string> {
    return btoa(
      String.fromCharCode.apply(
        null,
        new Uint8Array(await crypto.subtle.exportKey("spki", keys.publicKey))
      )
    );
  }
}
