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

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

  @ViewChild('f') definitionForm : NgForm;

  typePage: string = '';
  locations =[];
  valueType: string = '';
  checkSaveclick:boolean = false;
  check : boolean = false;
  isEdit: boolean = false;
  disable: boolean = false;
  editPageId: number;

  formData = {
    complex_number : '',
    name : '',
    land_area : '',
    status: '1',
    building_types:[
      {
      
        name : 'المباني',
        value : ''
},
{
        
        name : 'الفلل',
        value : ''
},
{
        
        name : 'العمائر',
        value: ''
},

    ]
  }
  

  ngOnInit() {

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

    if (this.editPageId) {
      this.spinner.show();
      this.formData.building_types = [];
      this.isEdit = true;
      this.typePage = 'تعديل';
      this.dashBoardSer.getItemData(this.editPageId, 'recordInfoBuilding' ).subscribe(
        res => {
          console.log('ssss', res);
          const array =res['housing_complex'].types;
          this.formData.complex_number = res['housing_complex'].complex_number;
          this.formData.name = res['housing_complex'].name;
          this.formData.land_area = res['housing_complex'].land_area;
          this.formData.status  = res['housing_complex'].status;
          for (let i = 0,n = array.length; i < n ; i++) {
          this.formData.building_types.push( res['housing_complex'].types[i]);
            
          }
          this.spinner.hide();
          console.log(this.formData);
          
        },
        err => {
          console.log(err);
        }
      );
    }else {
      this.typePage = 'اضافة';
    }
  }
  plusBuilding(){
    this.formData.building_types.push({
      name:'',
      value:''
    });
    console.log('forms after plus' , this.formData.building_types);
     }
     onDeleteRow(index:number) {
      this.formData.building_types.splice(index , 1);
      console.log('files after delete ',this.formData.building_types);
    }
    onSubmitted(){
    console.log('HERE',this.definitionForm.value);
    console.log(this.formData);
    for (let i = 0 , n = this.formData.building_types.length; i < n; i++) {
      const value =this.formData.building_types[i].value;
      const name = this.formData.building_types[i].name;
      console.log(name , value)
      if (value == '' || name == ''){
         this.formData.building_types.splice(i , 1); 
      }
      }
    
    this.disable = true;
    if(this.editPageId) {
      this.dashBoardSer.editItem(this.editPageId, this.formData, 'recordInfoBuilding').subscribe(
        res => {
          console.log(res);
          this.toastr.success('تم التعديل بنجاح');
          this.location.back();
          this.disable = false;

        },
        err => {
          console.log(err);
          if(err.error.error.complex_number[0] == 'The complex number has already been taken.'){
            this.toastr.warning('رقم المجمع موجود بالفعل')
            this.disable = false;
            
          }else{
          this.disable = false;

          this.toastr.error('خطأ في الخادم ، حاول لاحقا');
          }
        }
      )
    } else {
      this.dashBoardSer.addItem( this.formData , 'recordInfoBuilding').subscribe(
        res => {
          console.log('ADD',res);
          this.toastr.success('تم الإضافه بنجاح');
          this.checkSaveclick = false;
          this.disable = false;
          this.location.back();
        },
        err => {
          console.log(err.error.error.complex_number[0]);
          this.checkSaveclick = false;

          if(err.error.error.complex_number[0] == 'The complex number has already been taken.'){
            this.toastr.warning('رقم المجمع موجود بالفعل')
            this.disable = false;
            
          }else{
          this.disable = false;

          this.toastr.error('خطأ في الخادم ، حاول لاحقا');
          }

        }
      );
      }
  }

}
