import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { WebService } from './../../providers/web.service';
import { ValidationService } from './../../providers/validation.service';
import { FormControl, FormGroup, FormBuilder, Validators, ValidationErrors } from '@angular/forms';

@Component({
  selector: 'app-addforex',
  templateUrl: './addforex.component.html',
  styleUrls: ['./addforex.component.scss']
})
export class AddforexComponent implements OnInit {
  providerForm: FormGroup;
  mobnumPattern = '^((\\+?)|0)?[0-9]{9,10}$';
  emailPattern = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
  contactPattern = '[a-zA-Z ]*';
  providerSubmit: boolean;
  crId = '^((\\+?)|0)?[0-9]{10}$';
  lang =  'en';
  error_msg: any[];
  funcName: any;
  loader: boolean;
  responseError: any;
  error: boolean;
  success: boolean;
  providerList: any[];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    public vs: ValidationService,
    public service: WebService,
    private formBuilder: FormBuilder
    ) {
      this.loader = false;
      this.error = false;
      this.success = false;
      this.providerSubmit = false;
      this.error_msg = this.vs.errorList[this.lang];
    }

    ngOnInit() {
      this.getProvider();
      this.providerForm = this.formBuilder.group({
        'name':  ['', Validators.compose([Validators.required])],
        'cr_manager':  ['', Validators.compose([Validators.required])],
        'cr_id':  ['', Validators.compose([Validators.required, Validators.pattern(this.crId)])],
        'contact':  ['', Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z \-\']+')])],
        'location':  ['', Validators.compose([Validators.required])],
        'email_id': ['', Validators.compose([Validators.required, Validators.maxLength(50), Validators.pattern(this.emailPattern)])],
        // tslint:disable-next-line:max-line-length
        'phone':  ['', Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(15), Validators.pattern(this.mobnumPattern)])],
        'type':  [2],
        'online_status':  ['', Validators.compose([Validators.required])],
        'deli_provider_id': ['', Validators.compose([Validators.required])],
        'merchant_id': ['', Validators.compose([Validators.required])],
        'password': [''],
      });
    }

    goToPage(path, data = null) {
      console.log(data);
      this.router.navigateByUrl(path, {queryParams: data});
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    }

    regProcess() {
      const This = this;
      this.error = false;
      this.success = false;
      let pass =  Math.round(Math.random() * 1000000);
      pass = this.pad(pass, 6, 0);
      this.providerForm.controls['password'].setValue(pass);
      console.log(this.providerForm.value);
      this.providerSubmit = true;
      if (this.providerForm.valid) {
        this.loader = true;
        const providerObj = this.providerForm.value;
        this.funcName = 'provider_create';
        this.service.post_data(this.funcName, providerObj).subscribe(response => {
          this.loader = false;
          console.log(response);
          if (response.code === 1) {
            this.success = true;
            this.providerSubmit = false;
            this.providerForm.reset();
            this.providerForm.controls['type'].setValue(2);
          } else {
            this.error = true;
            this.responseError = this.vs.errorCode[this.lang][response.errorCode];
          }
        }, (error) => {
          this.error = false;
          this.responseError = this.vs.errorCode[this.lang]['ER08'];
        });
      }
      console.log('tested');
    }

    pad(n: any, width: any, z: any) {
      z = z || '0';
      n = n + '';
      return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    cancelClick() {
      this.router.navigate(['/maker/forex']);
    }

    getProvider() {
      this.loader = true;
      this.funcName = 'providers';
      const post_data = {'type': 3};
        this.service.post_data(this.funcName, post_data).subscribe(response => {
          this.loader = false;
          console.log(response);
          if (response.code === 1) {
            this.providerList = response.responseResult;
          } else {
            this.error = true;
            this.responseError = this.vs.errorCode[this.lang][response.errorCode];
          }
        }, (error) => {
          this.error = true;
          this.responseError =  this.vs.errorCode[this.lang]['ER08'];
      });
      const This = this;
      setTimeout(function() {
        This.responseError = '';
      }, 3000);
    }

    logout() {
      this.service.logout();
    }

}
