import { DashboardService } from './../../../shared/dashboard.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Subscription } 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';
import * as Quill from 'quill';


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

  constructor(private formBuilder: FormBuilder, 
    private hospitalService: HospitalService, 
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private toastr: ToastrService, 
    private authSer: AuthServiceService,
    private dashboardService: DashboardService,
    private location: Location) { }

  addHospitalForm: FormGroup;
  fields: FormArray;
  typeMode: boolean = false;
  checkSaveClick:boolean = false;
  typePageEdit: string = '';
  typeCreatePage: string = '';
  typeLink = 'إنشاء جديد';
  showAppearance: boolean = false;
  typeFirstLink: string;
  servicesType: string = '';
  typeId: number;
  editSubscription: Subscription;
  typeCreateSubscription: Subscription;
  fieldsData = [];
  
  serviceID:number;

  ngOnInit() {
    //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 
    

    //set side navigation bar 
    this.route.parent.params.subscribe(
      (params: Params) => {
        this.serviceID = params['serviceID'];
        if(params['serviceID'] == 2) {
          this.servicesType = 'خدمه إداره الصفحه الخارجيه';
        } else if(params['serviceID'] == 6) {
          this.servicesType = 'خدمه إداره المحتوي';
        }
      }
    );

    this.typeCreateSubscription = this.route.params.subscribe(
      (params: Params) => {
        this.typeCreatePage = params['typeAdd'];
        if(this.typeCreatePage == 'Hospital') {
          this.typeFirstLink = 'المستشفيات والمراكز';
          this.showAppearance = true;
          this.addHospitalForm = new FormGroup({
            name: new FormControl(null , Validators.required),
            name_en: new FormControl(null , Validators.required),
            display_location: new FormControl(null, Validators.required),
            fields: this.formBuilder.array([ this.createItem() ])
          });
        } else if(this.typeCreatePage == 'Management') {
          this.typeFirstLink = 'الإدارات';
          this.addHospitalForm = new FormGroup({
            name: new FormControl(null , Validators.required),
            name_en: new FormControl(null , Validators.required),
            fields: this.formBuilder.array([ this.createItem() ])
          });
        }
      }
    );

    //edit mode 
    this.editSubscription =  this.route.params.subscribe(
        (params: Params) => {
          if(params['typeHospitalMode'] == 'edithos') {
            this.spinner.show();
            this.typeLink = 'تعديل';
            this.typeFirstLink = 'المستشفيات والمراكز';
            this.showAppearance = true;
            this.addHospitalForm = new FormGroup({
              name: new FormControl(null , Validators.required),
              name_en: new FormControl(null , Validators.required),
              display_location: new FormControl(null, Validators.required),
              fields: this.formBuilder.array([])
            });
            this.spinner.show();
            this.typeMode = true;
            this.typePageEdit = 'edithos';
            this.typeId = +params['editTypePageId'];
            this.dashboardService.getItemData(this.typeId, 'hospital').subscribe(
              (responce) => {
                console.log('responcce', responce);
                this.fieldsData = responce['hospital_center'].fields;
                console.log(this.fieldsData);
                this.addHospitalForm.patchValue({
                  name: responce['hospital_center'].name,
                  name_en: responce['hospital_center'].name_en,
                  display_location: responce['hospital_center'].display_location,
                });
                  this.fields = this.addHospitalForm.get('fields') as FormArray;
                  for(let i = 0; i < this.fieldsData.length; i++) {
                    this.fields.push(
                      this.formBuilder.group({
                        title: this.fieldsData[i].title,
                        title_en: this.fieldsData[i].title_en,
                        description: this.fieldsData[i].description,
                        description_en: this.fieldsData[i].description_en, 
                      })
                    )
                  }
                  this.spinner.hide();
              },
              (error) => {
                console.log(error);
              }
            );
          } else if (params['typeHospitalMode'] == 'editman') {
            this.spinner.show();
            this.typeLink = 'تعديل';
            this.typeFirstLink = 'الإدارات';
            this.addHospitalForm = new FormGroup({
              name: new FormControl(null , Validators.required),
              name_en: new FormControl(null , Validators.required),
              fields: this.formBuilder.array([])
            });
            this.typeMode = true;
            this.typePageEdit = "editman";
            this.typeId = +params['editTypePageId'];

            this.typeId = +params['editTypePageId'];

            this.dashboardService.getItemData(this.typeId, 'managament').subscribe(
              (responce) => {
                console.log('responcce', responce);
                this.fieldsData = responce['management'].fields;
                this.addHospitalForm.patchValue({
                  name: responce['management'].name,
                  name_en: responce['management'].name_en,
                });
                  this.fields = this.addHospitalForm.get('fields') as FormArray;
                  for(let i = 0; i < this.fieldsData.length; i++) {
                    this.fields.push(
                      this.formBuilder.group({
                        title: this.fieldsData[i].title,
                        title_en: this.fieldsData[i].title_en,
                        description: this.fieldsData[i].description,
                        description_en: this.fieldsData[i].description_en,
                      })
                    )
                  }
                  this.spinner.hide();
              },
              (error) => {
                console.log(error);
              }
            );
          }
        }
      );
  };

  //to make at least on element in form array
  createItem(): FormGroup {
    return this.formBuilder.group({
      title: '',
      title_en: '',
      description: '',
      description_en: '',
    });
  };
 
  //add more title
  onAddTitle() {
    this.fields = this.addHospitalForm.get('fields') as FormArray;
    this.fields.push(this.createItem());
  }

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

  //submitted form
  onSubmitted() {
    this.checkSaveClick = true;
    console.log(this.addHospitalForm.value);
    const formHospitalData = this.addHospitalForm.value;
    console.log(formHospitalData.fields[0].title);

  if(this.typeCreatePage == 'Hospital') {
    if(formHospitalData.fields[0].title == '' || formHospitalData.fields[0].description == '') {
        this.toastr.warning('أدخل عنوان ووصف واحد علي الاقل !');
        this.checkSaveClick = false;
      } else {
        if(this.serviceID == 6) {
          this.dashboardService.addItem(formHospitalData, 'internalHospital').subscribe(
            (responce) => {
              this.checkSaveClick = false;
              console.log(responce);
              this.toastr.success('تم الاضافه بنجاح');
              this.location.back();
            },
            (error) => {
              this.checkSaveClick = false;
              this.toastr.error('خطأ في الإنشاء');
              console.log(error);
            }
          );
        } else if(this.serviceID == 2) {
          this.dashboardService.addItem(formHospitalData, 'externalHospital').subscribe(
            (responce) => {
              this.checkSaveClick = false;
              console.log(responce);
              this.toastr.success('تم الاضافه بنجاح');
              this.location.back();
            },
            (error) => {
              this.checkSaveClick = false;
              this.toastr.error('خطأ في الإنشاء');
              console.log(error);
            }
          );
        }
      }
    } else if(this.typeCreatePage == 'Management') {
      if(formHospitalData.fields[0].title == '' || formHospitalData.fields[0].description == '') {
          this.toastr.warning('أدخل عنوان ووصف واحد علي الاقل !');
          this.checkSaveClick = false;
        } else {
          if(this.serviceID == 6) {
            this.dashboardService.addItem(formHospitalData, 'internalManagement').subscribe(
              (responce) => {
                this.checkSaveClick = false;
                console.log(responce);
                this.toastr.success('تم الاضافه بنجاح');
                this.location.back();
              },
              (error) => {
                this.checkSaveClick = false;
                this.toastr.error('خطأ في الاضافه');
                console.log(error);
              }
            );
          } else if(this.serviceID == 2) {
            this.dashboardService.addItem(formHospitalData, 'externalManagement').subscribe(
              (responce) => {
                this.checkSaveClick = false;
                console.log(responce);
                this.toastr.success('تم الاضافه بنجاح');
                this.location.back();
              },
              (error) => {
                this.checkSaveClick = false;
                this.toastr.error('خطأ في الاضافه');
                console.log(error);
              }
            );
          }
        }
    }

    if(this.typeMode) {

      if(this.typePageEdit == 'edithos'){
        if(formHospitalData.fields[0].title == '' || formHospitalData.fields[0].description == '') {
          this.toastr.warning('أدخل عنوان ووصف واحد علي الاقل !');
          this.checkSaveClick = false;
        } else {
          if(this.serviceID == 6) {
            this.dashboardService.editItem(this.typeId, formHospitalData, 'internalHospital').subscribe(
              (responce) => {
                this.checkSaveClick = false;
                console.log(responce);
                this.toastr.success('تم التعديل بنجاح ');
                this.location.back();
              }, (error) => {
                this.checkSaveClick = false;
                console.log(error);
                this.toastr.error('فشل التعديل !');
              }
            );
          } else if(this.serviceID == 2) {
            this.dashboardService.editItem(this.typeId, formHospitalData, 'externalHospital').subscribe(
              (responce) => {
                this.checkSaveClick = false;
                console.log(responce);
                this.toastr.success('تم التعديل بنجاح ');
                this.location.back();
              }, (error) => {
                this.checkSaveClick = false;
                console.log(error);
                this.toastr.error('فشل التعديل !');
              }
            );
          }
        }
      } else if(this.typePageEdit == 'editman'){
        if(formHospitalData.fields[0].title == '' || formHospitalData.fields[0].description == '') {
          this.toastr.warning('أدخل عنوان ووصف واحد علي الاقل !');
          this.checkSaveClick = false;
        } else {
          if(this.serviceID == 6) {
            this.dashboardService.editItem(this.typeId, formHospitalData, 'internalManagement').subscribe(
              (responce) => {
                this.checkSaveClick = false;
                console.log(responce);
                this.toastr.success('تم التعديل بنجاح ');
                this.location.back();
              }, (error) => {
                this.checkSaveClick = false;
                console.log(error);
                this.toastr.error('فشل التعديل !');
              }
            );
          } else if(this.serviceID == 2) {
            this.dashboardService.editItem(this.typeId, formHospitalData, 'externalManagement').subscribe(
              (responce) => {
                this.checkSaveClick = false;
                console.log(responce);
                this.toastr.success('تم التعديل بنجاح ');
                this.location.back();
              }, (error) => {
                this.checkSaveClick = false;
                console.log(error);
                this.toastr.error('فشل التعديل !');
              }
            );
          }
        }
      }
    }

  };

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

}
