import {Component, OnInit, ViewChild, EventEmitter, Output} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {StepperComponent} from '@progress/kendo-angular-layout';
import {LoanSingleService} from '../service/loan.single.service';
import {LoanModel} from '../models/loan.model';
import {BasicinfoComponent} from './basicinfo/basicinfo.component';
import {ActivatedRoute, Router} from '@angular/router';
import {AuthService} from '../service/auth.service';


@Component({
  selector: 'app-loan-edit',
  templateUrl: './loan-edit.component.html',
  styleUrls: ['./loan-edit.component.scss']
})
export class LoanEditComponent implements OnInit {
  public submitted: boolean ;
  public currentStep = 0;
  @ViewChild('stepper', { static: true })  public stepper: StepperComponent;
  @ViewChild('basicInfo')  public basicInfo: BasicinfoComponent;
  @Output() LoanUpdated = new EventEmitter<LoanModel>();


  public Loan: LoanModel = new LoanModel({});
  public curStepSuccess = false;

  public showDelete = false;
  public navigateTo = '';

  public steps = [
    { label: 'Basic Info', isValid: true , errMsg: 'There are some errors'},
    { label: 'People', isValid: true , errMsg: 'There are some errors'},
    { label: 'Reward', isValid: true , errMsg: 'There are some errors'},
    { label: 'Trail Income', isValid: true, errMsg: 'There are some errors' }
  ];

  public dialogOpened = false;
  public errorMessage = '';

  constructor( private lss: LoanSingleService, private actRoute: ActivatedRoute, private auth: AuthService, private router: Router) { }

  public next(step: number, success: boolean): void {
    console.log(this.Loan);
    this.steps[step].isValid = success;
    if (step === this.currentStep) {
      this.curStepSuccess = success;
    }

    if ( this.curStepSuccess && (this.currentStep !== this.steps.length)) {
      this.currentStep += 1;

      return;
    }
    this.stepper.validateSteps();
  }

  public prev(step: number, event: boolean): void {
    console.log(step, event);
    this.currentStep -= 1;
  }


  ngOnInit(): void {
    const LoanId  = this.actRoute.snapshot.params.id;
    if ( LoanId !== undefined && LoanId.length > 10 ) {
      this.loadLoanById(LoanId);
    }else{
      this.startNewLoan();
    }
  }

  public del(): void {
    this.lss.deleteLoan(this.Loan.Id).subscribe(
      resp => {
        console.log(resp);
        this.showError('Loan' + resp + 'has been deleted');
        this.navigateTo = './#list-all-loans';
      },
      err => {
        this.showError('Error Occurred, cannot delete: ' + err.toString());
      }
    );
  }

  public loadLoanById(id: string): void {
    const self = this;
    // console.log('loading loan for edit ... ', id);
    this.lss.getLoan(id).subscribe(
      resp => {
        this.Loan.Response = resp;
        this.Loan.auth = this.auth;
        this.Loan.lss = this.lss;
        self.LoanUpdated.emit(this.Loan);
      }
    );
  }

  public startNewLoan(): void{
      this.Loan = LoanModel.EmptyNew(this.lss, this.auth);
  }

  public action(status): void {
    this.dialogOpened = false;
    if ( this.navigateTo !== '' ) {
      this.router.navigate([this.navigateTo]);
    }
  }

  public showError(msg: string): void{
    this.errorMessage = msg;
    this.dialogOpened = true;
  }

}
