import { Injectable } from "@angular/core";

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

    constructor(){ }

    validatePhoneNumber(input: string): [boolean, string] {
        var sanitized = input.replace(/\D/g, '');
        if (sanitized.length < 10){
            let formatted = sanitized.replace(/(\d{3})(?=\d{3})/g, '$1-').replace(/(\d{4})(?=\d{1,4}$)/, '$1-');
            return [false, formatted];
        } else if (sanitized.length === 10) {
            let result = `(${sanitized.slice(0, 3)})${sanitized.slice(3, 6)}-${sanitized.slice(6, 10)}`;
            return [true, result];
        } else if (sanitized.length > 10 && sanitized.length < 14) {
            let countryCode = sanitized.slice(0, sanitized.length - 10);
            let areaCode = sanitized.slice(sanitized.length - 10, sanitized.length - 7);
            let firstPart = sanitized.slice(sanitized.length - 7, sanitized.length - 4);
            let secondPart = sanitized.slice(sanitized.length - 4);
            let result = `+${countryCode} (${areaCode})${firstPart}-${secondPart}`;
            return [true, result];
        }else{
            return [false, input];
        }
    }

    emailRegex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    validateEmail(input: string): [boolean, string] {
        const corrected = input.trim().toLowerCase();
        const success = this.emailRegex.test(corrected);
        return [success, corrected];
    }

}