import { Validator, NG_VALIDATORS, FormControl } from '@angular/forms'
import { Directive, OnInit, forwardRef, Input } from '@angular/core';

import * as Globals from '../globals'; 
 
@Directive({
  selector: '[maxUtf8Length]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: MaxUtf8LengthValidator, multi: true }
  ]
})
export class MaxUtf8LengthValidator implements Validator, OnInit {
    @Input('maxUtf8Length') maxLength: string = '4096';
 
    ngOnInit() {
    }
 
    validate(c: FormControl) {
    
        let max: number = +this.maxLength;
        let len: number = Globals.lengthInUtf8Bytes(c.value);
    
        if (len > max) {
        return { utfLength: true, 'actualLength': len, 'maxAllowed': max }
        }
    
        return null;
    }
}