import { NgxSpinnerService } from 'ngx-spinner';
import { DashboardService } from './../../../shared/dashboard.service';import { HttpClient } from '@angular/common/http';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { Location, formatDate } from '@angular/common';
import { LocationListComponent } from '../../definition-of-location/location-list/location-list.component';
import { UserService } from 'src/app/shared/user.service';

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

  
  constructor(private route: ActivatedRoute, 
    private http: HttpClient,
    private toastr: ToastrService,
    private dashBoardSer: DashboardService,
    private spiner: NgxSpinnerService,
    private location: Location,
    private authService: AuthServiceService,
    private userService: UserService,
    private router: Router
    ) { }

    locationList = [];
    subLocationList = [];
    checkSaveClick: boolean = false;
    bindingDateSplitStart;
    checked : boolean = false;
    pageId: number;
    uploaded: boolean = false;
    disabledVal: boolean = true;
    serviceId: number;
    userId: number;

    files = [{
      title : null,
      file: null,
      file_type: null,
      nameFile: null,
    }];

    dataForm = {
      id_number: '',
      name : '',
      phoneNum: '',
      created_date : "",
      created_time : "",
      subject : '',
      message : '',
      main_location_id : '',
      sub_location_id : '',
      files: []
    };


  currentDate: any = Date.now();

       //higri date array
  month = ['محرم', 'صفر', 'ربيع الأول', 'ربيع الآخر', 'جمادى الأولى', 'جمادى الآخرة', 'رجب', 'Shaʻban', 'رمضان', 'شوال',
  'ذو القعدة', 'ذو الحجة'];



  ngOnInit() {

    //init the values of permision boolean
    this.authService.showAddBtn = false;
    this.authService.showDeleteBtn = false;
    this.authService.showEditBtn = false;
    //show / hide notification search in header
    this.authService.notificationLogin = true;
    this.authService.showSearchHeader = false;
    this.authService.showHeaderLogin = false;
    this.authService.showHeaderDashBoard = true;
    this.authService.showDashboardHeader = true;
    this.authService.internalHeader = false;
    
    this.route.params.subscribe(
      (parmas: Params) => {
        this.pageId =  +parmas['reportId'];
        localStorage.setItem('pageIdActive', parmas['reportId']);
      }
    );

    this.route.parent.params.subscribe(
      (params:Params) => {
        this.serviceId = params['serviceID'];
        this.userId = params['userID'];
      }
    );
   
    this.currentDate = this.authService.writeHijri(new Date(this.currentDate), 'en', 'system');



    

    const nowHigriDate = this.currentDate.split(' ');

    console.log('nowHigriDate', nowHigriDate);

    console.log('current higri date split', this.currentDate.split(' '));

    for(let i = 0; i < this.month.length; i++) {
      if(this.currentDate.split(' ')[0] == this.month[i]) {
        this.currentDate.split(' ')[0] = i + 1;
        nowHigriDate[0] = i + 1;
      }
    }

    this.bindingDateSplitStart = {
      year:parseInt(nowHigriDate[2]),
      month: parseInt(nowHigriDate[0]),
      day: parseInt(nowHigriDate[1]),
    }

    console.log('hhhhhhhhhhhhhhhhhhhh', this.bindingDateSplitStart);



    var today = new Date();
    this.dataForm.created_time = ( today.getHours() > 10 ? today.getHours() : '0' + today.getHours() ) + ":" + ( today.getMinutes() > 10 ? today.getMinutes() : '0' + today.getMinutes() );
    console.log('created_timmmmme', this.dataForm.created_time);
    this.dataForm.created_date = nowHigriDate[2] + '-' + nowHigriDate[0] + '-' + nowHigriDate[1];

    console.log('dataForm object ', this.dataForm.created_date);

    this.http.get(this.authService.pathApi + '/parent_locations_list').subscribe(
      (response) => {
        this.locationList = response['locations'];
        console.log(response)
      },
      (error) => {
        console.log(error);
      }
    );

    this.http.get(this.authService.pathApi + '/profile').subscribe(
      (responce) => {
       this.dataForm.id_number = responce['user'].identity_number;
       this.dataForm.name = responce['user'].name;
       this.dataForm.phoneNum = responce['user'].phone
       console.log('dsf',responce)
      },
      (error) => {console.log(error)},
    );

  }
  
  onChangemainLocation(event){
   const id = event.target.value
   this.dataForm.main_location_id = id;
    this.http.get(this.authService.pathApi + '/childs_locations_list_by_parent_id/' + id).subscribe(  
      (response)  => {
        console.log(id);
        this.subLocationList = response['locations'];
        
      },
      (error) => {
        console.log(error)
      }
     );
  }

  
  changeSubLocation(event){
    console.log(event.target.value);
    this.dataForm.sub_location_id = event.target.value;
  }

  plusImage() {
    this.files.push({
      title: null,
      file: null,
      file_type: null,
      nameFile: null,
    });
    console.log('files after plus ', this.files);
  }
 
 //delete row from table
 onDeleteRow(index:number) {
  this.files.splice(index , 1);
  console.log('files after delete ',this.files);
}
  //change file 
  onFileChanges(event, index:number) {
    console.log(event);
    console.log(index);
    this.uploaded = true;
    this.files[index].nameFile = event[0].name.substring(0,20) + '....';
    this.files[index].file = event[0].base64;
    this.files[index].file_type = event[0].type.split('/')[1];
      console.log(this.files);
      console.log('files after change ',this.files);
  }
  
  onSubmitted(){
    for (let i = 0; i < this.files.length; i++) {
      if(this.files[i].file_type){
        this.files[i].file_type = this.files[i].file_type.toLowerCase();
      }
      if(this.files[i].file != null && this.files[i].title == null){
       this.toastr.warning('ادخل عنوان الملف رقم ' + (i+1) );
       this.checked = true;
      }else if(this.files[i].file == null && this.files[i].title != null){
        this.files.splice(i , 1);
      }else if(this.files[i].file == null && this.files[i].title == null){
        this.files.splice(i , 1);
       } else {
       delete this.files[i].nameFile;
        this.dataForm.files.push(this.files[i]);
      }

      
    }
    if(!this.checked){
      delete this.dataForm.id_number;
      delete this.dataForm.name;
      delete this.dataForm.phoneNum;
      if(this.dataForm.files.length == 0 ){
        delete this.dataForm.files;
      }
    console.log(this.dataForm);
   this.http.post(this.authService.pathApi + '/add_communication' , this.dataForm )
      .subscribe(
         res => {
           console.log(res);
           this.checked = false;
           this.toastr.success('تم حفظ البلاغ ');
           this.router.navigate(['/service/' + this.userId + '/' +  this.serviceId + '/followCommunicationList/58']);
          },
          err => {
           console.log(err)
           this.toastr.error('حدث خطأ في الاتصال ');
          }
       );
    }else{
      console.log('i cant send the request');
    }
  
    }
}
