/*
 * Copyright (C) 2019 Robert Bosch GmbH Copyright (C) 2019 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { ScrollIntoViewService } from '../../shared/scroll-into-view.service';
import { NotificationService } from '@bci-web-core/core';

const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'bci-input-field-demo',
  templateUrl: 'input-field-demo.html',
  styleUrls: ['input-field-demo.scss'],
})
export class InputFieldDemoComponent {
  inputWidth = '300px';
  floatingLabel = 'always';
  color: boolean;
  requiredField = new FormControl(false);
  hideRequiredMarker = new FormControl(false);
  ctrlDisabled = false;
  textareaNgModelValue: string;

  name: string;
  errorMessageExample1: string;
  errorMessageExample2: string;
  errorMessageExample3: string;
  errorMessageExample4: string;
  items: any[] = [{ value: 10 }, { value: 20 }, { value: 30 }, { value: 40 }, { value: 50 }];
  formControl = new FormControl('hello', Validators.required);
  matErrorControl = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
  emailFormControl = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
  emailFormControl2 = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
  emailFormControl3 = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
  emailFormControl4 = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
  emailFormControl5 = new FormControl('', [Validators.required, Validators.pattern(EMAIL_REGEX)]);
  delayedFormControl = new FormControl('');
  drinksControl = new FormControl('', Validators.required);
  model = 'hello';
  hide = true;
  customErrorStateMatcher: ErrorStateMatcher = {
    isErrorState: (control: FormControl | null) => {
      if (control) {
        const hasInteraction = control.dirty || control.touched;
        const isInvalid = control.invalid;

        return !!(hasInteraction && isInvalid);
      }

      return false;
    },
  };

  isSearchInputFocused = false;
  searchInput = '';

  constructor(public scrollIntoViewService: ScrollIntoViewService,private notify: NotificationService) {
    setTimeout(() => this.delayedFormControl.setValue('hello'), 100);
  }

  searchSubmit() {
    this.notify.information('On click of input search', '', undefined, '', '');
  }

  get isEmailWarning2() {
    return this.emailFormControl2.value.length > 0 && this.emailFormControl2.value.length < 10;
  }

  get isEmailWarning3() {
    return this.emailFormControl3.value.length > 0 && this.emailFormControl3.value.length < 10;
  }

  get isEmailSuccess3() {
    return !this.isEmailWarning3 && !this.emailFormControl3.errors;
  }

  get isEmailWarning4() {
    return this.emailFormControl4.value.length > 0 && this.emailFormControl4.value.length < 10;
  }

  get isEmailSuccess4() {
    return !this.isEmailWarning4 && !this.emailFormControl4.errors;
  }

  get isEmailWarning5() {
    return this.emailFormControl5.value.length > 0 && this.emailFormControl5.value.length < 10;
  }

  get isEmailSuccess5() {
    return !this.isEmailWarning5 && !this.emailFormControl5.errors;
  }

  numberPrecision(number: number): number {
    if (Math.floor(number.valueOf()) === number.valueOf()) {
      return 0;
    }
    return number.toString().split('.')[1].length || 0;
  }

  stepUp(element: HTMLInputElement, event) {
    event.stopPropagation();
    try {
      // go native if implemented
      element.stepUp();
    } catch (e) {
      // using a polyfill alternative
      this.step(element, +1);
    }
  }

  stepDown(element: HTMLInputElement, event) {
    event.stopPropagation();
    try {
      // go native if implemented
      element.stepDown();
    } catch (e) {
      // using a polyfill alternative
      this.step(element, -1);
    }
  }

  private step(element: HTMLInputElement, direction: number) {
    // stepping a number
    const value = parseFloat(element.value || '0');
    const step = parseFloat(element.step || '1');
    const minValue = isNaN(parseFloat(element.min)) ? -Infinity : parseFloat(element.min);
    const maxValue = isNaN(parseFloat(element.max)) ? Infinity : parseFloat(element.max);
    const precision = this.numberPrecision(step);
    const scalc = (value + step * direction).toFixed(precision);
    const calc = parseFloat(scalc);

    if (calc < minValue) {
      element.value = minValue + '';
    } else if (calc > maxValue) {
      element.value = maxValue + '';
    } else {
      element.value = calc + '';
    }
  }
}
