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-edit-driver',
  templateUrl: './edit-driver.component.html',
  styleUrls: ['./edit-driver.component.scss']
})
export class EditDriverComponent 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[];
  loginDetails: any;
  userDetails: 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.loginDetails =  JSON.parse(this.service.getLocalStorageItem('userData'));
    this.getProfile();
    this.getProvider(id);
    console.log(id);
    this.providerForm = this.formBuilder.group({
      'manager_id':  ['', Validators.compose([Validators.required])],
      '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':  [4],
      'driver_id': [id],
      'national_id':  [''],
      'postal': ['', Validators.compose([Validators.required])],
      'max_amount': ['', Validators.compose([Validators.required])],
      'max_limit': ['', Validators.compose([Validators.required])],
      'deli_provider_id': ['', Validators.compose([Validators.required])]
    });
  }

  getProvider(id: any) {
    this.loader = true;
    this.funcName = 'driver_details';
    const post_data = {'driver_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;
          this.providerForm.patchValue({
            manager_id: this.provider.manager_id,
            postal: this.provider.postal,
            location: this.provider.location,
            email_id: this.provider.email_id,
            phone: this.provider.phone,
            max_amount: this.provider.max_amount,
            max_limit: this.provider.max_limit,
            national_id: this.provider.national_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);
  }

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

  cancelClick() {
    this.router.navigate(['/delivery/driverlist']);
  }

  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 = 'driver_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;
        } 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');
  }

  getProfile() {
    this.funcName = 'get_user_details';
    const post_data = {'user_id': this.loginDetails.user_id};
    this.service.post_data(this.funcName, post_data).subscribe(response => {
      if (response.code === 1) {
        this.userDetails = response.responseResult;
        this.providerForm.controls['deli_provider_id'].setValue(this.userDetails.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'];
  });
  }

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

}
