import { Injectable } from '@angular/core';
import {TranslateService} from "@ngx-translate/core";

@Injectable({
  providedIn: 'root'
})
export class ValidationService {
  public static notEmpty = (value?: string) => {
    const check = !ValidationService.isNullOrEmpty(value);
    return check || 'VALIDATION.NOT_EMPTY';
  };

  public static email = (value?: string) => {
    //const check = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(value!);
    
    const check = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value!);
    return check || "VALIDATION.VALID_EMAIL";
  };

  public static equalTo(otherV?: string) {
    return (value?: string) => {
        const check = !ValidationService.isNullOrEmpty(otherV) && !ValidationService.isNullOrEmpty(value) && otherV === value;
        return check || "VALIDATION.PASSWORD_NOT_THE_SAME";
    }
  }

  public static securePassword = (value?: string) => {
    var regex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
    const check = regex.test(value!);
    return check || "VALIDATION.PASSWORD_SHOULD_BE";
  };

  constructor(
      private translateService: TranslateService
  ) {}

  validate(validators: any[]) {
    let result: any[] = [];
    if (validators && validators.length > 0) {
      this.translateService.get(["VALIDATION.NOT_EMPTY", "VALIDATION.VALID_EMAIL", "VALIDATION.PASSWORD_NOT_THE_SAME", "VALIDATION.PASSWORD_SHOULD_BE"]).subscribe(translate => {
        validators.forEach(o => {
          o.validators.forEach((v:any) => {
            const check = v(o.value);
            if (typeof(check) == 'string') result.push({name: o.name, message: translate[check]});
          })
        });
      });
    }
    return result;
  }

  public static isNullOrEmpty(str: any): boolean {
    var returnValue = false;

    if (typeof str == 'object') {
      if (!str || str.length < 1) returnValue = true;
    }
    if (typeof str == 'number') {
      if (('' + str).length < 1) returnValue = true;
    }
    else if (
        !str
        || str == null
        || str === 'null'
        || str === ''
        || str === '{}'
        || str === 'undefined'
        || str.length === 0
        || (str.replace && str.replace(/\s/g, '').length < 1)) {
      returnValue = true;
    }
    return returnValue;
  }
}
