import { HttpClient } from '@angular/common/http';
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-registration-vehicle-add',
  templateUrl: './registration-vehicle-add.component.html',
  styleUrls: ['./registration-vehicle-add.component.css']
})
export class RegistrationVehicleAddComponent implements OnInit {

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

  @ViewChild('f') vehicleForm : NgForm;

  typePage: string = '';
  checkSaveclick:boolean = false;
  vehicleId: number;
  vehicle_types:any[] = [];
  modelNames:any[] = [];
  registerVehicleId: number;

  formData = {
    vehicle_status: '',
    vehicle_type_id: '',
    vehicle_model_id: '',
    sub_name: '',
    structure_number: '',
    plate_number: '',
    color: ''
  }

  ngOnInit() {

      //init the values of permision boolean
      this.authSer.showAddBtn = false;
      this.authSer.showDeleteBtn = false;
      this.authSer.showEditBtn = false;
      //show / hide notification search in header
      this.authSer.notificationLogin = true;
      this.authSer.showSearchHeader = false;
      this.authSer.showHeaderLogin = false;
      this.authSer.showHeaderDashBoard = true;
      this.authSer.showDashboardHeader = true;
      this.authSer.internalHeader = false;

      this.http.get(this.authSer.pathApi + '/get_vehicle_types_list').subscribe(
        (response) => {
          console.log(response);
          this.vehicle_types = response['types'];
          
        },
        (error) => {
          console.log(error);
        });

        this.route.params.subscribe(
          (params: Params) => {
            this.registerVehicleId = params['registrationVehicleEditId'];
          }
        );

        if(this.registerVehicleId) {
          this.spinner.show();
          this.dashBoardSer.getItemData(this.registerVehicleId, 'registerVehicle').subscribe(
            (responce) => {
              console.log(responce);
              this.formData.color = responce['data'].color;
              this.formData.plate_number = responce['data'].plate_number;
              this.formData.structure_number = responce['data'].structure_number;
              this.formData.sub_name = responce['data'].sub_name ? responce['data'].sub_name : '';
              this.formData.vehicle_model_id = responce['data'].vehicle_model_id;
              this.formData.vehicle_status = responce['data'].vehicle_status;
              this.formData.vehicle_type_id = responce['data'].vehicle_type_id;
              this.getModelName(this.formData.vehicle_type_id);
              this.spinner.hide();
            },
            (error) => {
              console.log(error);
            }
          );
        }
       

  }

  onChangeVehicleType(event) {
    const typeId = event.target.value;
    this.getModelName(typeId);
  }

  getModelName(typeVehicleId) {
    this.http.get(this.authSer.pathApi + '/get_vehicle_models_by_type_id/' + typeVehicleId).subscribe(
      (responce) => {
        console.log('types names of vehicles ', responce);
        this.modelNames = responce['models'];
        if(this.modelNames.length == 0) {
          this.toastr.warning('لا يوجد اسماء موديل لهذا النوع');
        }
      },
      (error) => {
        console.log(error);
      }
    )
  }


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

}
