import { DashboardService } from './../../../shared/dashboard.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { UserService } from './../../../shared/user.service';
import { ActivatedRoute, Params } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Location } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-add-visiting-time',
  templateUrl: './add-visiting-time.component.html',
  styleUrls: ['./add-visiting-time.component.css']
})
export class AddVisitingTimeComponent implements OnInit {
  @ViewChild('f') dataForm: NgForm;

  constructor(private userSer:UserService,
    private authSer:AuthServiceService,
    private toastr: ToastrService,
    private spinner: NgxSpinnerService,
    private dashboardSer: DashboardService,
    private location: Location,
    private route:ActivatedRoute) { }
    typeMode:boolean = false; //default false for create page
    typeLink: string;
    visitingTimeId:number;
    checkDisabledSave:boolean = false;

    visitingTime = {
      name: '',
      name_en: '',
      open_time: '',
      close_time: '',
      status: 1,
    };

    ngOnInit() {
      this.route.params.subscribe(
        (params: Params) => {
          if(params['typeVisitingTime'] == 'add'){
            this.typeMode = false;
            this.typeLink = 'إنشاء موعد';
          } else if(params['typeVisitingTime'] == 'edit') {
            this.spinner.show();
            this.typeMode = true;
           this.visitingTimeId = parseInt(localStorage.getItem('editvisitingTimeIdStorage'));
            this.typeLink = 'تعديل موعد';
            this.dashboardSer.getItemData(this.visitingTimeId, 'visitingTime').subscribe(
              (responce) => {
                console.log(responce);
                this.visitingTime = responce['visiting_time'];
                console.log(this.visitingTime);

                this.spinner.hide();
              },
              (error) => {
                console.log(error);
              }
            );

          } else {
            console.log('Catch Error Go To Home !');
          }
        }
      );


    }//ngOnInit


    onSubmitted() {
      this.checkDisabledSave = true;
      const dataFormContactUs = this.dataForm.value;

      console.log(dataFormContactUs)
      if(this.typeMode) {

        this.dashboardSer.editItem( this.visitingTimeId,dataFormContactUs, 'visitingTime').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم التعديل بنجاح ');
            this.checkDisabledSave = false;
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.checkDisabledSave = false;
            this.toastr.error(' خطأ في التعديل !');
          }
        );
      }
    }

}
