import { DashboardService } from './../../../shared/dashboard.service';
import { FooterService } from './../../../shared/footer.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'app-add-footer',
  templateUrl: './add-footer.component.html',
  styleUrls: ['./add-footer.component.css']
})
export class AddFooterComponent implements OnInit {

  @ViewChild('f') footerFormData: NgForm;

  urlImg: string =  '../../assets/image/avatar.png';
  imageBase64: string = '';
  photoType: string = '';
  checkChangeImage: boolean = false;
  checkValidImg: boolean = true;
  typeMode: boolean = false;
  photoEdit: boolean = true;
  typeLink: string = '';
  externalId: number;
  serviceId: number;
  //to show emeil || description || link
  showEmailField: boolean = false;
  showLinkField: boolean = false;
  showDescriptionField: boolean = false;
  checkContactUs:boolean = false;
  checkOtherField: boolean = false;
  checkNotContactUs:boolean = false;
  contactUsPage: boolean = false;
  serviceName: string = '';

  footer = {
    name: '',
    name_en: '',
    link: '',
    status: '',
    type: '',
    email: '',
    description: '',
    description_en: '',
  };

  constructor(private toastr: ToastrService, 
    private spinner: NgxSpinnerService,
    private location: Location,
    private authSer: AuthServiceService,
    private route: ActivatedRoute,
    private dashBoardService: DashboardService,
    private footerService: FooterService) { }

  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.route.parent.params.subscribe(
      (params: Params) => {
        this.serviceId = params['serviceID'];
        if(this.serviceId == 2) {
          this.serviceName = 'خدمه إداره الصفحه الخارجيه';
        } else if (this.serviceId == 6) {
          this.serviceName = 'خدمه إداره المحتوي';
        }
      }
    );
    
    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeFooterMode'] == 'edit') {
          this.typeLink = 'تعديل';
          this.spinner.show();
          this.typeMode = true;
          this.externalId = params['editFooterId'];
          this.dashBoardService.getItemData(this.externalId, 'footer').subscribe(
            (responce) => {
              console.log(responce['footer']);
              this.footer.name = responce['footer'].name;
              this.footer.name_en = responce['footer'].name_en;
              if(this.footer.name == 'تواصل معنا' || this.footer.name_en == 'contact us') {
                this.showEmailField = true;
                this.showDescriptionField = false;
                this.showLinkField = false;
                this.footer.description = '';
                this.footer.description_en = '';
                this.footer.link = '';
                this.contactUsPage = true;
              } else {
                this.checkNotContactUs = true;
                this.showDescriptionField = true;
                this.showEmailField = false;
                this.showLinkField = false;
                this.footer.email = '';
                this.footer.link = '';
                
              }
              this.footer.link = responce['footer'].link;
              this.footer.status = responce['footer'].status;
              this.footer.type = responce['footer'].type;
              this.footer.email = responce['footer'].email;
              this.footer.description = responce['footer'].description;
              this.footer.description_en = responce['footer'].description_en;
              if(responce['footer'].photo) {
                this.checkValidImg = false;
                this.urlImg = this.authSer.pathImg + responce['footer'].photo;
              }
              this.spinner.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        } else {
          this.typeLink = 'إنشاء جديد';
        }
      }
    );

  }



  onFileChanges(event) {
    console.log(event);
    this.imageBase64 = event[0].base64;
    this.photoType = event[0].type.split('/');
    console.log(this.photoType[1]);
    //console.log(this.imageBase64);
    this.checkChangeImage = true;
    this.checkValidImg = false;
  }

  getUrl(event) {   
    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 = event.target['result'];
    }
  }
 }

 onChangeType(event) {
   console.log(event.target.value);
   this.footer.type = event.target.value;
   if(event.target.value == 0 && this.showEmailField == true) {
    this.showDescriptionField = true;
    this.showLinkField = false;
    this.footer.link = '';
    this.footer.description = '';
    this.footer.description_en = '';
   } else if(event.target.value == 0 && this.checkNotContactUs == true) {
      this.showDescriptionField = true;
      this.showLinkField = false;
      this.showEmailField = false;
      this.footer.link = '';
      this.footer.email = '';
   } else if(event.target.value == 1 || event.target.value == 2 || this.showDescriptionField) {
    this.showLinkField = true;
    this.showEmailField = false;
    this.showDescriptionField = false;
    this.footer.description = '';
    this.footer.description_en = '';
    this.footer.email = '';
   } else {
     if(this.contactUsPage) {
      this.showDescriptionField = false;
      this.showEmailField = true;
      this.showLinkField = false;
      this.footer.link = '';
      this.footer.description = '';
      this.footer.description_en = '';
     } else {
      this.showDescriptionField = true;
      this.showEmailField = false;
      this.showLinkField = false;
      this.footer.email = '';
      this.footer.link = '';
     }
   }
 }

 //on submitted
 onSubmitted() {
  const formData = this.footerFormData.value;
  console.log(formData);
 
  if(this.checkChangeImage){
    formData['photo'] = this.imageBase64;
    formData['photo_type'] = this.photoType[1];
  } else {
    delete formData.photo;
    delete formData.photo_type; 
    this.photoEdit = false;
    console.log(formData);
  }
  if(this.typeMode){
    if(this.photoType[1] != 'png' && this.photoEdit == true) {
      this.toastr.warning('الصوره يجب أن تكون بصيغه Png');
    } else if(this.imageBase64 == '' && this.photoEdit == true){
      this.toastr.warning('قم باختيار صوره !');
    } else {
      if(this.serviceId == 2) {
        this.dashBoardService.editItem( this.externalId, formData, 'internalFooter').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت التعديل بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في التعديل !');
          }
        );
      } else if(this.serviceId == 6){
        this.dashBoardService.editItem( this.externalId, formData, 'externalFooter').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت التعديل بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في التعديل !');
          }
        );
      }
    }
  } else {
    if(this.photoType[1] != 'png') {
      this.toastr.warning('الصوره يجب أن تكون بصيغه Png');
    } else if(this.imageBase64 == ''){
      this.toastr.warning('قم باختيار صوره !');
    } else {
      // formData['photo'] = this.imageBase64;
      // formData['photo_type'] = this.photoType[1];
      if(this.serviceId == 2) {
        this.dashBoardService.addItem(formData, 'externalFooter').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت الاضافه بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في الحفظ !');
          }
        );
      } else if(this.serviceId == 6){
        this.dashBoardService.addItem(formData, 'internalFooter').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت الاضافه بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في الحفظ !');
          }
        );
      }
    }
  }
  

 }


}
