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


@Component({
  selector: 'app-add-news',
  templateUrl: './add-news.component.html',
  styleUrls: ['./add-news.component.css']
})
export class AddNewsComponent implements OnInit {

  @ViewChild('f') newForm: NgForm;
  typeMode: boolean = false;
  newId: number;
  checkChangeImage: boolean = false;
  checkValidImg: boolean = true;
  imageBase64: string = '';
  photoType: string = '';
  typeLink: string = '';
  photoEdit:boolean = true;


  new = {
    title: '',
    title_en: '',
    ranking: '',
    display_location: '',
    type: '',
    status: '',
    description: '',
    description_en: '',
  }

  urlImg: string =  '../../assets/image/avatar.png';

  

  constructor(private newService: NewService,
    private userService: UserService,
    private authSer: AuthServiceService,
    private location: Location,
    private toastr: ToastrService,
    private route: ActivatedRoute, 
    private authService: AuthServiceService,
    private spineer: NgxSpinnerService) { }

  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.route.params.subscribe(
      (params: Params) => {
        if(params['typeNewMode'] == 'edit') {
          this.typeLink = 'تعديل';
          this.spineer.show();
          this.typeMode = true;
          this.newId = params['editNewId'];
          this.newService.getNewData(this.newId).subscribe(
            (responce) => {
              console.log(responce);
              const newData = responce['report'];
              console.log(newData);
              this.new.title = newData.title;
              this.new.title_en = newData.title_en;
              this.new.ranking = newData.ranking;
              this.new.display_location = newData.display_location;
              this.new.type = newData.type;
              this.new.status = newData.status;
              this.new.description = newData.description;
              this.new.description_en = newData.description_en;
              if(responce['report'].photo) {
                this.checkValidImg = false;
                this.urlImg = this.authService.pathImg + responce['report'].photo;
              }
              this.spineer.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'];
    }
  }
 }

  //submitted form
  onSubmitted() {
    const formData = this.newForm.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){
      if(this.photoType[1] != 'png' && this.photoEdit == true) {
        this.toastr.warning('الصوره يجب أن تكون بصيغه Png');
      } else if(this.imageBase64 == '' && this.photoEdit == true){
        this.toastr.warning('قم باختيار صوره !');
      } else {
        // formData['photo'] = this.imageBase64;
        // formData['photo_type'] = this.photoType[1];
        this.newService.editNew(formData, this.newId).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];
        this.newService.addNew(formData).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت الاضافه بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في الحفظ !');
          }
        );
      }
    }
  }
}
