import { NgxSpinnerService } from 'ngx-spinner';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from './../../../shared/dashboard.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-vehicle-add',
  templateUrl: './vehicle-add.component.html',
  styleUrls: ['./vehicle-add.component.css']
})
export class VehicleAddComponent implements OnInit {

  constructor(private dashBoardSer: DashboardService, 
    private toastr: ToastrService, 
    private authSer: AuthServiceService, 
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private location: Location) { }

  @ViewChild('f') vehicleForm : NgForm;

  typePage: string = '';
  checkSaveclick:boolean = false;
  vehicleId: number;


  formData = {
    name: '',
    status: '',
  }

  ngOnInit() {

    this.route.params.subscribe(
      (params: Params) => {
        this.vehicleId = params['vehicleEditId'];
      }
    )
    
    if(this.vehicleId) {
      this.spinner.show();
      this.typePage = 'تعديل';
      this.dashBoardSer.getItemData(this.vehicleId, 'vehicle').subscribe(
        (responce) => {
          console.log(responce);
          this.formData.name = responce['type'].name;
          this.formData.status = responce['type'].status;
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
        }
      )
    } else {
      this.typePage = 'إضافه';
    }
  }


  onSubmitted() {


    this.checkSaveclick = true;
    
    if(this.vehicleId) {
      this.dashBoardSer.editItem(this.vehicleId, this.vehicleForm.value, 'vehicle').subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم التعديل بنجاح ');
          this.location.back();
        },
        (error) => {
          console.log(error);
          this.toastr.error('يوجد خطأ في الخادم ، حاول لاخقا');
        }
      )
    } else {
      //add submitted
      this.dashBoardSer.addItem(this.vehicleForm.value, 'vehicle').subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم الإضافه بنجاح');
          this.location.back();
        },
        (error) => {
          this.checkSaveclick = false;
          console.log(error);
          this.toastr.error('خطا في السيرفر ، حاول لاحقاً !');
        }
      );
    }
    
    console.log(this.vehicleForm);
  }

}
