import { DashboardService } from './../../../shared/dashboard.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { ExternalSerService } from './../../../shared/external-ser.service';
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-external',
  templateUrl: './add-external.component.html',
  styleUrls: ['./add-external.component.css']
})
export class AddExternalComponent implements OnInit {

  @ViewChild('f') externalFormData: NgForm;

  urlImg: string =  '../../assets/image/avatar.png';
  imageBase64: string = '';
  photoType: string = '';
  checkChangeImage: boolean = false;
  checkValidImg: boolean = true;
  typeMode: boolean = false;
  photoEdit: boolean = true;
  checkSaveClick:boolean = false;
  typeLink: string = '';
  externalId: number;
  serviceId: number;
  external = {
    name: '',
    name_en: '',
    link: '',
    status: '',
    ranking: '',
    type: '',
    description: '',
    description_en: '',
  };

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

  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;
    this.external.status = "1";

    this.route.parent.params.subscribe(
      (params: Params) => {
        this.serviceId = params['serviceID'];
      }
    );

    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeExternalMode'] == 'edit') {
          this.spinner.show();
          this.typeMode = true;
          this.typeLink = 'تعديل';
          this.externalId = params['editExternalId'];
          this.dashBoardService.getItemData(this.externalId, 'externalService').subscribe(
            (responce) => {
              console.log(responce['external_service']);
              this.external.name = responce['external_service'].name;
              this.external.name_en = responce['external_service'].name_en;
              this.external.link = responce['external_service'].link;
              this.external.status = responce['external_service'].status;
              this.external.ranking = responce['external_service'].ranking;
              this.external.type = responce['external_service'].type;
              this.external.description = responce['external_service'].description;
              this.external.description_en = responce['external_service'].description_en;
              if(responce['external_service'].photo) {
                this.checkValidImg = false;
                this.urlImg = this.authService.pathImg + responce['external_service'].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]);
    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'];
    }
  }
 }

 changeType(event) {
   console.log(event.target.value);
   this.external.type = event.target.value;
   if(event.target.value == 'internal') {
     this.external.link = '';
   } else if(event.target.value == 'external') {
     this.external.description = '';
     this.external.description_en = '';
   } else {
     console.log('no choice');
   }
 }

 //on submitted
 onSubmitted() {

  this.checkSaveClick = true;
  const formData = this.externalFormData.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.imageBase64 == '' && this.photoEdit == true) {
      this.toastr.warning('قم باختيار صوره !');
      this.checkSaveClick = false;
    } else if((this.photoType[1] != 'png' && this.photoType[1] != 'gif') && this.photoEdit == true){
      this.toastr.warning('الصوره يجب أن تكون بصيغه Png');
      this.checkSaveClick = false;
    } else {
      if(this.serviceId == 6) {
        this.dashBoardService.editItem( this.externalId, formData, 'internalServiceExternalPage').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت التعديل بنجاح');
            this.location.back();
            this.checkSaveClick = true;
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
            if(error.error['status'] == 'active status for only 6 records') {
              this.toastr.warning('لقد تخطيت الحد الأقصي للخدمات ، قم بعدم تفعيل أو مسح أحدهم');
            } else {
              this.toastr.error('خطأ في السيرفر ، ستتم المعالجه لاحقاً !');
            }
          }
        );
      } else if(this.serviceId == 2) {
        this.dashBoardService.editItem( this.externalId, formData, 'externalServiceExternalPage').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت التعديل بنجاح');
            this.location.back();
            this.checkSaveClick = true;
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
            if(error.error['status'] == 'active status for only 6 records') {
              this.toastr.warning('لقد تخطيت الحد الأقصي للخدمات ، قم بعدم تفعيل أو مسح أحدهم');
            } else {
              this.toastr.error('خطأ في السيرفر ، ستتم المعالجه لاحقاً !');
            }
          }
        );
      }
    }
  } else {
    if(this.imageBase64 == '') {
      this.toastr.warning('قم باختيار صوره !');
      this.checkSaveClick = false;
    } else if(this.photoType[1] != 'png' && this.photoType[1] != 'gif'){
      this.toastr.warning('الصوره يجب أن تكون بصيغه Png');
      this.checkSaveClick = false;
    } else {
      if(this.serviceId == 6){
        this.dashBoardService.addItem(formData, 'internalServiceExternalPage').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت الاضافه بنجاح');
            this.location.back();
            this.checkSaveClick = true;
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
            if(error.error['status'] == 'active status for only 6 records') {
              this.toastr.warning('لقد تخطيت الحد الأقصي للخدمات ، قم بعدم تفعيل أو مسح أحدهم');
            } else {
              this.toastr.error('خطأ في السيرفر ، ستتم المعالجه لاحقاً !');
            }
          }
        );
      } else if(this.serviceId == 2){
        console.log(formData);
        this.dashBoardService.addItem(formData, 'externalServiceExternalPage').subscribe(
          (responce) => {
          this.toastr.success('تمت الاضافه بنجاح');
          this.location.back();
          this.checkSaveClick = true
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
            if(error.error['status'] == 'active status for only 6 records') {
              this.toastr.warning('لقد تخطيت الحد الأقصي للخدمات ، قم بعدم تفعيل أو مسح أحدهم');
            } else {
              this.toastr.error('خطأ في السيرفر ، ستتم المعالجه لاحقاً !');
            }
          }
        );
      }

    }
  }
 }


}
