import { HttpClient } from '@angular/common/http';
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 http: HttpClient,
    private location: Location) { }

  addInternalForm: FormGroup; //form group
  fields: FormArray; //form array fields inside form group
  typeMode: boolean = false; //to check edit or create
  //typePageEdit: string = '';
  //typeCreatePage: string = '';
  typeLink = 'إنشاء جديد'; //type path text create or edit 
  pageId: number; //pageId for edit 
  editSubscription: Subscription; //subscription edit 

  //editObjectPhoto = [];
  lastIndex:number; //to get the last index of checkChangeImage on photo case in edit
  fieldsData = []; //to in edit mode collect all fields in this array
  internalPages = [];
  
  //array of photos data 
  imageBase64 = [{
    photo: '',
    photo_type: '',
  }];

  checkChangeImage = [false]; //check change for any image if change in edit mode or no
  urlImg =  ['../../assets/image/avatar.png'];

  checkSaveClick:boolean = false; //to make button save disabled when submitted form
  checkAdd:boolean = false; //to check on edit or create mode to send id in edit mode 
  photoType: string = ''; //type of photos

  checkValidateField: boolean = false; //to send save if all validation of fields is true

  showLink: boolean = false;

  
  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;

    this.internalServices.getInternalPages().subscribe(
      (responce) => {
        console.log(responce);
        this.internalPages = responce['pages'];
      },
      (error) => {
        console.log(error);
      }
    )
    
    
    //init form data 
    this.addInternalForm = new FormGroup({
      name: new FormControl(null , Validators.required),
      name_en: new FormControl(null , Validators.required),
      status: new FormControl('1', 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 = [];
            this.checkChangeImage = [];
            //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.addInternalForm.patchValue({
                  name: responce['internal_service'].name,
                  name_en: responce['internal_service'].name_en,
                  status: responce['internal_service'].status,
                });

                this.fieldsData = responce['internal_service'].fields;

                console.log(this.fieldsData);
      
                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,
                        photo: this.fieldsData[i].photo,
                        status: this.fieldsData[i].status,
                        link_type: this.fieldsData[i].link_type,
                        link: this.fieldsData[i].link,
                        link2: this.fieldsData[i].link2,
                      })
                    )
                  }

                  //for loop to append url photo to array to show it
                  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.checkChangeImage[i] = false;
                    this.imageBase64[i] = {
                      photo: this.fieldsData[i].photo ? this.fieldsData[i].photo : '',
                      photo_type: 'edit'
                    }
                  }

                  //this.lastIndex = this.checkChangeImage.length;

                  console.log('edit image base 64' , this.imageBase64);
                  console.log('edit check change image', this.checkChangeImage);
                  console.log('edit mode url image ' , this.urlImg);
                  this.spinner.hide();
              },
              (error) => {
                console.log(error);
              }
            );
          } else{
            this.typeLink = 'إنشاء جديد';
          }
        }
      );
  };

  //to make at least on element in form array
  createItem(): FormGroup {
    if(this.typeMode) {
      return this.formBuilder.group({
        name: '',
        name_en: '',
        photo: '',
        link: '',
        status: '1',
        link_type: '',
        link2: ''
      });
    } else {
      return this.formBuilder.group({
        name: '',
        name_en: '',
        photo: '',
        photo_type: '',
        link: '',
        status: '1',
        link_type: '',
        link2: '',
      });
    }
    
  };
 
  //add more title
  onAddTitle() {
    
    this.fields = this.addInternalForm.get('fields') as FormArray;
    this.fields.push(this.createItem());
    this.urlImg.push('../../assets/image/avatar.png');
    this.checkChangeImage.push(false);

    //create mode
    this.imageBase64.push({
      photo: '',
      photo_type: '',
    });
 
    this.checkAdd = true;
    console.log('image base 64',this.imageBase64);
    console.log('check change image', this.checkChangeImage);
    console.log('url images', this.urlImg);
  }

  //remove from array form
  removeTitle(index: number) {
    this.fields = this.addInternalForm.get('fields') as FormArray;
    this.fields.removeAt(index);
    this.imageBase64.splice(index,1);
    this.urlImg.splice(index, 1);
    this.checkChangeImage.splice(index, 1);
    console.log('image base 64',this.imageBase64);
    console.log('check change image', this.checkChangeImage);
    console.log('url images', this.urlImg);
  }


//upload image 
  onFileChanges(event,i) {
    console.log(event);
    alert(i);
    this.checkChangeImage[i] = true;
    var id_field = ''; //to get id of field from fields 
    if(this.typeMode) {  
      //edit mode we have two case if change photo or add new item
      if(!this.checkAdd) {
        id_field = this.fieldsData[i].id;
         //the data of photo user changed it 
        const dataUploadEdit = {
          field_id : id_field,
          photo: event[0].base64,
          photo_type: event[0].type.split('/')[1].toLowerCase(),
        };

        //to check validate type of photo and send it to backend
        if(dataUploadEdit.photo_type != 'png') {
          if(dataUploadEdit.photo_type != 'gif') {
            this.toastr.warning('الصوره بصيغه png أو gif');
          }
        } else {
          //send photo change request
          this.http.post(this.authSer.pathApi + '/upload_internal_service_field' , dataUploadEdit ).subscribe(
            (responce) => {
              console.log(responce['photo']);
            },
            (error) => {
              console.log(error);
            }
          )
        }
      } else {
          //to collect all image base64 of photo upload in craete case
          this.photoType = event[0].type.split('/');
          this.imageBase64[i]={
            photo : event[0].base64,
            photo_type: this.photoType[1].toLowerCase(),
          };
          this.checkChangeImage[i] = true;
          console.log(' cheeck change iamge' , this.checkChangeImage);
          console.log('base 64 images',this.imageBase64);
      }
    } else {
      //to collect all image base64 of photo upload in craete case
      this.photoType = event[0].type.split('/');
      this.imageBase64[i]={
        photo : event[0].base64,
        photo_type: this.photoType[1].toLowerCase(),
      };
      this.checkChangeImage[i] = true;
      console.log(' cheeck change iamge' , this.checkChangeImage);
      console.log('base 64 images',this.imageBase64);
    }
  }

  //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('url images' , this.urlImg[i]);
    }
  }
 }

 //to show link internal or external depend on value of radio button
 showCahngeRadio(type,index) {
  this.showLink = type;
  const fieldsValue = this.addInternalForm.get('fields')
  if(type == 'internal') {
    console.log(this.addInternalForm.get('fields')['controls'][index]['controls'].link.value = null);
    this.addInternalForm.get('fields')['controls'][index]['controls'].link.value = null
  } else if (type == 'external') {
    console.log(this.addInternalForm.get('fields')['controls'][index]['controls'].link2.value = null);
    this.addInternalForm.get('fields')['controls'][index]['controls'].link2.value = null
  }
 }





   //submitted form
   onSubmitted() {

    this.checkSaveClick = true;

    const formInternalData = this.addInternalForm.value;
    console.log(formInternalData);


    //edit mode
    if(this.typeMode) {

      //save edit
     

      for(let i = 0; i < this.imageBase64.length; i++) {
        if(this.imageBase64[i].photo_type == 'edit') {
          formInternalData['fields'][i].photo = this.imageBase64[i].photo;
        } else {
          formInternalData['fields'][i].photo = this.imageBase64[i].photo;
          formInternalData['fields'][i].photo_type = this.imageBase64[i].photo_type;
        }
      }
      

      console.log(formInternalData);

      //validateion in data fields
      for(let i = 0; i < formInternalData['fields'].length; i++) {
        if(formInternalData['fields'][i].photo == '') {
          this.toastr.warning('قم باختيار صوره للعنصر ' + (i+1) );
          this.checkValidateField = true;
          this.checkSaveClick = false;
        } else if(formInternalData['fields'][i].name == '' || formInternalData['fields'][i].name_en == '' || formInternalData['fields'][i].apperance == '' || formInternalData['fields'][i].status == ''){
          this.toastr.warning('من فضلك قم بإكمال بيانات العنصر ' + (i + 1) );
          this.checkValidateField = true;
          this.checkSaveClick = false;this.checkValidateField = true;
          this.checkSaveClick = false;
        } else {
          this.checkValidateField = false;
          this.checkSaveClick = true;
        }
      }

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

    } else {
      //save create 


      //for loop to add photo & photo type in form data 
      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('form data',formInternalData);
  
      //for loop for validation of fields 

      for(let i=0; i< formInternalData['fields'].length; i++) {
        if(formInternalData['fields'][i].photo == '') {
          this.checkValidateField = true;
          this.checkSaveClick = false; 
          this.toastr.warning('من فضلك  قم بإدخال صوره العنصر ' + ' ' + (i + 1) );
        } else if(formInternalData['fields'][i].photo_type != 'png') {
          if(formInternalData['fields'][i].photo_type != 'gif') {
            this.toastr.warning(' يجب أن تكون الصوره بصيغه png او gif للعنصر' + ' ' + (i + 1) );
          }
          this.checkValidateField = true;
          this.checkSaveClick = false;
        }else if(formInternalData['fields'][i].name == ''  || formInternalData['fields'][i].status == '') {
          this.toastr.warning('من فضلك قم بإكمال بيانات العنصر ' + (i + 1) );
          this.checkValidateField = true;
          this.checkSaveClick = false;
        }
        else {
          console.log('rightImage');
          this.checkSaveClick = true;
          this.checkValidateField = false;
        }
      }

      if(this.checkValidateField) {
        console.log('logical images error');
      }else {
        this.internalServices.addInternal(formInternalData).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم الاضافه بنجاح');
            this.location.back();
            this.checkSaveClick = false;
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
          }
        );
      }
    }

  };

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


}
