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-unit-building-information-add',
  templateUrl: './unit-building-information-add.component.html',
  styleUrls: ['./unit-building-information-add.component.css']
})
export class UnitBuildingInformationAddComponent implements OnInit {

  typePage: string = '';
  isComplex = false;
  isBuildingType = false;
  show_amount = false;
  amount = [];
  complex_list =[];
  building_types=[];
  buildings = [];
  valueType: string = '';
  checkSaveclick:boolean = false;
  check : boolean = false;
  isEdit: boolean = false;
  editPageId: number;
  disable: boolean =  false;

  constructor(
    private dashBoardSer: DashboardService,
    private toastr: ToastrService,
    public authSer: AuthServiceService,
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private location: Location,
    private http: HttpClient
  ) { }
  @ViewChild('f') unitInfoForm : NgForm;

  formData = {
    housing_complex_id:'',
    building_type_id:'',
    building_id: '',
    unit_number:'',
    unit_code:'',
    unit_name:'',
    bedrooms_number:'',
    bathrooms_number:'',
    sittingrooms_number:'',
    independent_kitchen:'0',
    unit_status:'new',
    description:'',
    status: '1',
  }

  ngOnInit() {

    this.route.params.subscribe(
      (params: Params) => {
        this.editPageId = +params['listPageEditId'];
        console.log(this.editPageId);
      }
    );

    this.http.get(this.authSer.pathApi + '/housing_complexes_list').subscribe(
      res => {
        console.log(res);
        this.complex_list = res[('housing_complexes')];
      }
    );

    if (this.editPageId) {
      
      this.isEdit = true;
      this.typePage = 'تعديل';
      this.dashBoardSer.getItemData(this.editPageId, 'unitBuildingInformation' ).subscribe(
        res => {
          console.log('ssss', res);
          this.formData.housing_complex_id = res['unit_information'].housing_complex_id;
          this.getBuildingsType(this.formData.housing_complex_id);
          this.formData.building_type_id = res['unit_information'].building_type_id;
          this.getBuilding(this.formData.building_type_id);
          this.formData.building_id = res['unit_information'].building_id;
          // this.typeNumber(this.formData.building_id);
          this.formData.unit_number = res['unit_information'].unit_number;
          this.formData.unit_code = res['unit_information'].unit_code;
          this.formData.unit_name = res['unit_information'].unit_name;
          this.formData.bedrooms_number = res['unit_information'].bedrooms_number;
          this.formData.bathrooms_number = res['unit_information'].bathrooms_number;
          this.formData.sittingrooms_number = res['unit_information'].sittingrooms_number;
          this.formData.independent_kitchen = res['unit_information'].independent_kitchen;
          this.formData.unit_status = res['unit_information'].unit_status;
          this.formData.description = res['unit_information'].description;
          this.formData.status = res['unit_information'].status;
          
        },
        err => {
          console.log(err);
        }
      );
     
    }else {
      this.typePage = 'اضافة';
    }

  }

  getBuildingsType(event){
    console.log('sdsdsd',event);
    const id = event;
    this.isComplex = false;
    this.isBuildingType = false;
    this.show_amount = false;
 
  console.log(id);
    this.building_types = []
    this.http.get(this.authSer.pathApi+ '/building_types_list/' + id ).subscribe(
      res => {
        console.log(res);
        this.building_types = res[('building_types')];
        if(this.building_types.length > 0)
         this.isComplex = true;
         else {
           this.isComplex = false;
           this.isBuildingType = false;
        }
          if(this.editPageId){
            this.getBuilding(this.formData.building_type_id);
          }
      },
      err => {
        console.log(err);
        
      }
    );  
  } 
  
  getBuilding(event){
    this.buildings = []
      this.http.get(this.authSer.pathApi + '/buildings_list_by_type_id/' + event ).subscribe(
        res => {
          console.log(res);
          this.buildings = res['buildings'];
          if(this.buildings.length > 0){
            this.isBuildingType = true;
            console.log(this.buildings);

          }else{
               this.isBuildingType = false;
               this.show_amount = false;
               this.toastr.warning('لا يوجد بيانات لهذا النوع من المباني')
            }

            if(this.editPageId) {
              this.typeNumber(this.formData.building_id);}
        },
        err => {
          console.log(err);
          
        }
      );
  }
  typeNumber(event){
    this.amount =[]
    this.show_amount = true;
  const id = event;;
  for (let i = 0; i < this.buildings.length; i++) {
    if(id == this.buildings[i].id) {
        this.amount = this.buildings[i].empty_ids; 
        console.log('ammmmounnnt', this.amount);
        if(this.amount.length == 0){
          this.toastr.warning('لا يوجد وحدات فارغة')
          this.show_amount = false;
        }
        this.amount.push(this.formData.unit_number);

    }
  } 

  }
  onSubmitted(){
    console.log('HERE',this.unitInfoForm.value);
    this.disable = true;
    if(this.editPageId) {
      this.dashBoardSer.editItem(this.editPageId, this.unitInfoForm.value, 'unitsBuildingInformation').subscribe(
        res => {
          console.log(res);
          this.toastr.success('تم التعديل بنجاح');
          this.location.back();
          this.disable = false;
        },
        err => {
          console.log(err);
          this.toastr.error('خطأ في الخادم ، رجاء المحارله لاحقا');
          this.disable = false;

        }
      )
    } else {
      this.dashBoardSer.addItem( this.unitInfoForm.value , 'unitsBuildingInformation').subscribe(
        res => {
          console.log('ADD',res);
          this.toastr.success('تم الإضافه بنجاح');
          this.checkSaveclick = false;
          this.location.back();
          this.disable = false;

        },
        err => {
          console.log(err);
          this.checkSaveclick = false;
          this.disable = false;
          this.toastr.error('خطأ في الخادم ، حاول لاحقا');
        }
      );
      }
  }

}
