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-editprovider',
  templateUrl: './editprovider.component.html',
  styleUrls: ['./editprovider.component.scss']
})
export class EditproviderComponent 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];
    this.loginDetails = JSON.parse(this.service.getLocalStorageItem('userData'));
  }

  ngOnInit() {

    this.getProfile();
    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':  [3],
      'provider_id': []
    });
  }

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

  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;
        } 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.provider = response.responseResult;
          this.providerForm.patchValue({
            cr_manager: this.provider.cr_manager,
            contact: this.provider.contact,
            location: this.provider.location,
            email_id: this.provider.email_id,
            provider_id: this.provider.id,
            phone: this.provider.phone
          });
      } 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'];
    });
  }

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

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

}
