import { InternalSerService } from './../../../shared/internal-ser.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Subscription, empty } from 'rxjs';
import { Location } from '@angular/common';
import { HospitalService } from './../../../shared/hospital.service';
import { FormGroup,FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';


@Component({
  selector: 'app-add-internal-services',
  templateUrl: './add-internal-services.component.html',
  styleUrls: ['./add-internal-services.component.css']
})

export class AddInternalServicesComponent implements OnInit {

  constructor(private formBuilder: FormBuilder, 
    private internalServices: InternalSerService, 
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private toastr: ToastrService, 
    private authSer: AuthServiceService,
    private location: Location) { }

  addInternalForm: FormGroup;
  fields: FormArray;
  typeMode: boolean = false;
  typePageEdit: string = '';
  typeCreatePage: string = '';
  typeLink = 'إنشاء جديد';
  pageId: number;
  editSubscription: Subscription;
  typeCreateSubscription: Subscription;
  fieldsData = [];
  imageBase64 = [];
  photoType: string = '';
  checkChangeImage = [false];
  showOpenFile = [true];
  showCloseFile = [false];
  urlImg =  ['../../assets/image/avatar.png'];
  i = 0;
  
  ngOnInit() {
    //show / hide notification search in header
    this.authSer.notificationLogin = true;
    this.authSer.showSearchHeader = false;
    this.authSer.showHeaderLogin = false;
    this.authSer.showHeaderDashBoard = true;
     //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;
    
    //init form data 
    this.addInternalForm = new FormGroup({
      name: new FormControl(null , Validators.required),
      name_en: new FormControl(null , Validators.required),
      status: new FormControl(null, Validators.required),
      fields: this.formBuilder.array([ this.createItem() ])
    });


    //edit mode 
    this.editSubscription =  this.route.params.subscribe(
        (params: Params) => {
          if(params['typeInternalMode'] == 'edit') {
            
            this.typeLink = 'تعديل';
            this.imageBase64 = [];
            //redifine form data
            this.addInternalForm = new FormGroup({
              name: new FormControl(null , Validators.required),
              name_en: new FormControl(null , Validators.required),
              status: new FormControl(null, Validators.required),
              fields: this.formBuilder.array([])
            });

            this.spinner.show();
            this.typeMode = true;
            this.pageId = params['editInternalId'];

            this.internalServices.getInternalData(this.pageId).subscribe(
              (responce) => {
                console.log('responcce', responce);
                this.fieldsData = responce['internal_service'].fields;
                console.log(this.fieldsData);
                this.addInternalForm.patchValue({
                  name: responce['internal_service'].name,
                  name_en: responce['internal_service'].name_en,
                  status: responce['internal_service'].status,
                });
                  
                this.fields = this.addInternalForm.get('fields') as FormArray;
                  
                for(let i = 0; i < this.fieldsData.length; i++) {
                    this.fields.push(
                      this.formBuilder.group({
                        name: this.fieldsData[i].name,
                        name_en: this.fieldsData[i].name_en,
                        link: this.fieldsData[i].link,
                        apperance: this.fieldsData[i].apperance,
                        status: this.fieldsData[i].status,
                      })
                    )
                  }

                  for(let i=0; i<this.fieldsData.length; i++) {
                    this.urlImg[i] = this.fieldsData[i].photo ? this.authSer.pathImg + this.fieldsData[i].photo : '../../assets/image/avatar.png';
                    this.showCloseFile[i] = true;
                    this.showOpenFile[i] = false;
                    this.checkChangeImage[i] = false;
                  }

                  this.spinner.hide();
              },
              (error) => {
                console.log(error);
              }
            );
          } else{
            this.typeLink = 'إنشاء جديد';
          }
        }
      );
  };

  //to make at least on element in form array
  createItem(): FormGroup {
    return this.formBuilder.group({
      name: '',
      name_en: '',
      photo: '',
      link: '',
      apperance: '',
      status: '',
    });
  };
 
  //add more title
  onAddTitle(i) {
    this.fields = this.addInternalForm.get('fields') as FormArray;
    this.fields.push(this.createItem());
    this.imageBase64[this.i] = [{
      photo : "",
      photo_type: "",
    }];
    this.i++;
    console.log(this.imageBase64);
    this.urlImg.push('../../assets/image/avatar.png');
    this.showOpenFile.push(true);
    this.showCloseFile.push(false);
    this.checkChangeImage.push(false);
  }

  //remove from array form
  removeTitle(index: number) {
    this.fields = this.addInternalForm.get('fields') as FormArray;
    this.fields.removeAt(index);
  }



  onFileChanges(event,i) {

    console.log(event);
    this.photoType = event[0].type.split('/');
    console.log(i);

    this.imageBase64[i]={
      photo : event[0].base64,
      photo_type: this.photoType[1],
    };

    console.log(this.imageBase64);

    this.checkChangeImage[i] = true;
    this.showCloseFile[i] = true;
    this.showOpenFile[i] = false;

  }

  //to upload url to view
  getUrl(event,i) {   
    if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]); // read file as data url
    reader.onload = (event) => { // called once readAsDataURL is completed
      this.urlImg[i] = event.target['result'];
      console.log(this.urlImg[i]);
    }
  }
 }

 //to close and upload photo
 closePhoto(i) {
    this.showCloseFile[i] = false;
    this.showOpenFile[i] = true;
    this.urlImg[i] =  '../../assets/image/avatar.png';
    this.imageBase64[i] = {
      photo: "",
      photo_type: "",
    }
    console.log(this.imageBase64);
 }


   //submitted form
   onSubmitted() {

    const formInternalData = this.addInternalForm.value;
    
    for(let i = 0; i< formInternalData['fields'].length; i++) {
      for(let j = 0; j < this.imageBase64.length; j++) {
        formInternalData['fields'][i].photo = this.imageBase64[i].photo;
        formInternalData['fields'][i].photo_type = this.imageBase64[i].photo_type;
      }
    }

    console.log(formInternalData);

    if(formInternalData['fields'].length == 0) {
      this.toastr.warning('أدخل عنوان ووصف واحد علي الاقل !');
    } else if(formInternalData['fields'][0].name == '' || formInternalData['fields'][0].apperance == '' || formInternalData['fields'][0].status == '') {
      this.toastr.warning('أدخل عنوان ووصف واحد علي الاقل !');
    } else {
        this.internalServices.addInternal(formInternalData).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم الاضافه بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
          }
        );
    }


    if(this.typeMode) {
      this.internalServices.editInternal(this.pageId, formInternalData).subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم التعديل بنجاح ');
        }, (error) => {
          console.log(error);
          this.toastr.error('فشل التعديل !');
        }
      );
    }

  };

  ngOnDestroy() {
    this.editSubscription.unsubscribe();
  }


}
