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-contact-us',
  templateUrl: './add-contact-us.component.html',
  styleUrls: ['./add-contact-us.component.css']
})
export class AddContactUsComponent 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;
    contactUsId:number;
    checkDisabledSave:boolean = false;

    contactUs = {
      field: '',
      field_en: '',
    };



  ngOnInit() {

    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeContactUs'] == 'edit') {
          this.spinner.show();
          this.typeMode = true;
          this.contactUsId = parseInt(localStorage.getItem('editcontactUsIdStorage'));
          this.typeLink = 'تعديل محتوي الصفحة';
          this.dashboardSer.getItemData(this.contactUsId, 'contactUs').subscribe(
            (responce) => {
              console.log(responce);
              this.contactUs = responce['contact_us'];
              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;
    if(this.typeMode) {

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


}
