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-editforex',
  templateUrl: './editforex.component.html',
  styleUrls: ['./editforex.component.scss']
})
export class EditforexComponent implements OnInit {
  provider: any;
  funcName: any;
  lang =  'en';
  responseMsg: any;
  error: boolean;
  success: boolean;
  loader: boolean;
  providerForm: FormGroup;
  mobnumPattern = '^((\\+?)|0)?[0-9]{8,15}$';
  emailPattern = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
  providerSubmit: boolean;
  error_msg: any[];
  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() {
    const parm = decodeURIComponent(this.route.snapshot.params['id']);
    // tslint:disable-next-line:radix
    const id = parseInt(parm);

    this.getProvider(id);
    this.getProviderList();
    console.log(id);
    this.providerForm = this.formBuilder.group({
      'cr_manager':  ['', Validators.compose([Validators.required])],
      '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],
      'users_id': [''],
      'provider_id': [id],
      'online_status':  ['', Validators.compose([Validators.required])],
      'deli_provider_id': ['', Validators.compose([Validators.required])],
      'merchant_id': ['', Validators.compose([Validators.required])],
      'status': [''],
    });
  }

  getProviderList() {
    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.responseMsg = this.vs.errorCode[this.lang][response.errorCode];
        }
      }, (error) => {
        this.error = true;
        this.responseMsg =  this.vs.errorCode[this.lang]['ER08'];
    });
    const This = this;
    setTimeout(function() {
      This.responseMsg = '';
    }, 3000);
  }

  getProvider(id: any) {
    this.loader = true;
    this.funcName = 'providers_details';
    const post_data = {'provider_id': id};
      this.service.post_data(this.funcName, post_data).subscribe(response => {
        this.loader = false;
        console.log(response);
        if (response.code === 1) {
          this.provider = response.responseResult;
          console.log(this.provider);
          this.providerForm.patchValue({
            cr_manager: this.provider.cr_manager,
            contact: this.provider.contact,
            location: this.provider.location,
            email_id: this.provider.email_id,
            phone: this.provider.phone,
            online_status: this.provider.online_status,
            deli_provider_id: this.provider.deli_provider_id,
            status: this.provider.status,
            merchant_id: this.provider.merchant_id,
            users_id: this.provider.users_id
          });
        } else {
          this.error = true;
          this.responseMsg = this.vs.errorCode[this.lang][response.errorCode];
        }
      }, (error) => {
        this.error = true;
        this.responseMsg =  this.vs.errorCode[this.lang]['ER08'];
    });

    const This = this;
    setTimeout(function() {
      This.responseMsg = '';
    }, 3000);
  }

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

  editProcess() {
    const This = this;
    this.error = false;
    this.success = false;
    console.log(this.providerForm.value);
    this.providerSubmit = true;
    if (this.providerForm.valid) {
      this.loader = true;
      const providerObj = this.providerForm.value;
      this.funcName = 'provider_edit';
      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.getProvider(providerObj.provider_id);
        } else {
          this.error = true;
          this.responseMsg = this.vs.errorCode[this.lang][response.errorCode];
        }
      }, (error) => {
        this.error = false;
        this.responseMsg = this.vs.errorCode[this.lang]['ER08'];
      });
    }
    console.log('tested');
  }

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

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

}
