import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { environment } from '../../environments/environment';
// import { ToastrService } from '../components/toastr/toastr.service';
import * as CryptoJS from 'crypto-js';

@Injectable({
  providedIn: 'root'
})
export class SharedService {

  constructor(
    // private _toast: ToastrService,
  ) { }

  // tslint:disable-next-line:typedef
  public currentLang = new Subject<string>();
  public handleHttpErrorResponse(err) {
    let errorCode = '';
    let noApiFlag = false;
    if (err && err.url) {
      const apiEndPointPath = err.url;
      if (apiEndPointPath) {
        const array = apiEndPointPath.split('/');
        if (array.length > 0) {
          const endpoint = array[array.length - 1];
          errorCode += `: ${endpoint.toUpperCase()}`;
        } else {
          noApiFlag = true;
        }
      } else {
        noApiFlag = true;
      }
    } else {
      noApiFlag = true;
    }
    if (noApiFlag) {
      errorCode = '';
    }
    this.serviceErrorMessage(environment.serviceUnavailableMessage + errorCode);
  }

  // tslint:disable-next-line:typedef
  public serviceErrorMessage(message?) {
    console.log("Service Error: ",message);
    // this._toast.toast('error', 'Failed', message, true);
    // const alertConf: AlertConfig = { type: 'error', title: 'Failed', body: message };
    // this.alert.open(alertConf);
  }
  // tslint:disable-next-line:typedef
  public internalCodeError(message?) {
    console.log("Internal code Error: ",message);

    // this._toast.toast('error', 'Failed', message.error || 'Internal code error', true);
    // const alertConf: AlertConfig = {
    //   type: 'error', title: 'Failed', body: message.error || 'Internal code error'
    // };
    // this.alert.open(alertConf);
  }

  public AESencrypt(value: string, key: string): string {
    try {

      return CryptoJS.AES.encrypt(value, key);
    } catch (e) {
      console.error(e);
    }
  }
  public AESdecrypt(textToDecrypt: string, key: string) {
    try {
      key = CryptoJS.enc.Utf8.parse(key);
      
    const ciphertext = CryptoJS.enc.Base64.parse(textToDecrypt);
    // split IV and ciphertext
    const iv = ciphertext.clone();
    iv.sigBytes = 16;
    iv.clamp();
    ciphertext.words.splice(0, 4); // delete 4 words = 16 bytes
    ciphertext.sigBytes -= 16;

    // decryption
    const decrypted = CryptoJS.AES.decrypt({ ciphertext }, key, {
      iv,
    });
    const decryptedString = decrypted.toString(CryptoJS.enc.Utf8);
    return decryptedString;
    } catch (e) {
      console.error(e);
    }
  }
  getDisabledStatus(cls) {
    if ($('.' + cls).length > 0) {
      $('.' + cls)[0].focus();
      return true;
    } else {
      return false;
    }
  }

  getCurrentLang() {
    return this.currentLang;
  }

  setCurrentLang(lang) {
    this.currentLang.next(lang);
  }
}
