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-advertising-service',
  templateUrl: './add-advertising-service.component.html',
  styleUrls: ['./add-advertising-service.component.css']
})
export class AddAdvertisingServiceComponent 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) { }

    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 = '';
    advertisingId: number;
    checkDisabledSave:boolean = false;


    advertising = {
      name: '',
      name_en: '',
      position: '',
      type: '',
      link: '',
      description: '',
      description_en: '',
      status: 1,
    };


    ngOnInit() {


      this.route.params.subscribe(
        (params: Params) => {
          console.log(params)
          if(params['typeAdvertising'] == 'add'){
            this.typeMode = false;
            this.typeLink = 'إنشاء خدمة إعلانية';
          } else if(params['typeAdvertising'] == 'edit') {
            this.spinner.show();
            this.typeMode = true;
            this.advertisingId = parseInt(params.advertisingId);
            this.typeLink = 'تعديل خدمة إعلانية';
            this.dashboardSer.getItemData(this.advertisingId, 'advertising').subscribe(
              (responce) => {
                console.log(responce);
                this.advertising = responce['advertising_service'];
                console.log(this.advertising);
                if(responce['advertising_service'].photo) {
                  this.checkValidImg = false;
                  this.urlImg = this.authSer.pathImg + responce['advertising_service'].photo;
                }
                this.spinner.hide();
              },
              (error) => {
                console.log(error);
              }
            );

          } else {
            this.toastr.warning('Catch Error Go To Home !');
          }
        }
      );


    }//ngOnInit



    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'];
      }
    }
  }

  onSubmitted() {
    this.checkSaveClick = true;
    const formData = this.dataForm.value;
    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) {

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

      this.dashboardSer.addItem(formData,'advertising').subscribe(
        (responce) => {
          this.toastr.success('تم الاضافه بنجاح');
          this.checkDisabledSave = false;
          console.log(responce);
          this.location.back();
        },
        (error) => {
          console.log(error);
          this.checkDisabledSave = false;
          this.toastr.error('خطأ في الاضافه');
        }
      );
    }
  }





}
