import { Injectable } from "@angular/core";
import * as CryptoJS from 'crypto-js';

export class CommonService{
    static yek = "$uPer@dm1n~dI@z7";

    private static encryptText(plainText) {
        var key = CryptoJS.enc.Utf8.parse(this.yek);
        var iv = CryptoJS.enc.Utf8.parse(this.yek);

        var encryptedText = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plainText), key,
            {
                keySize: 128 / 8,
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            }).toString();
        return encryptedText;
    }
    
    public static decryptText(cipherText) {
        var key = CryptoJS.enc.Utf8.parse(this.yek);
        var iv = CryptoJS.enc.Utf8.parse(this.yek);

        var decryptedText = CryptoJS.AES.decrypt(cipherText, key,
            {
                keySize: 128 / 8,
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            }).toString(CryptoJS.enc.Utf8);
        return decryptedText;
    }
    public static setSessionStorage(key: string, value) {
        sessionStorage.setItem(key, this.encryptText(value));
    }
    
    public static getSessionStoage(key: string) {
        var value = sessionStorage.getItem(key);
        if (value) {
            return this.decryptText(value);
        } else return null;
    }
    public static resetLocalStoage(key: string) {
        localStorage.removeItem(key);
    }
    public static setLocalStoage(key: string, value) {
        value = JSON.stringify(value);
        localStorage.setItem(key, this.encryptText(value));
    }

    public static getLocalStoage(key: string) {
        var value = localStorage.getItem(key);
        if (value) {
            return JSON.parse(this.decryptText(value));
        }
    }
}