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-adver',
  templateUrl: './add-adver.component.html',
  styleUrls: ['./add-adver.component.css']
})
export class AddAdverComponent implements OnInit {

  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;
    fileUpload: any;
    checkChangePhoto:boolean = false;
    advertisimenId:number;
    @ViewChild('f') formAdvertisimentData: NgForm;


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

    advertisiment = {
      start_time: '',
      end_time: '',
      status: 1,
      description: '',
      description_en: '',
    }

  ngOnInit() {
    
    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeAdver'] == 'add'){
          this.typeMode = false;
          this.typeLink = 'إنشاء إعلان';
        } else if(params['typeAdver'] == 'edit') {
          this.spinner.show();
          this.typeMode = true;
         this.advertisimenId = parseInt(localStorage.getItem('editAdevIdStorage'));
          this.typeLink = 'تعديل إعلان';
          this.dashboardSer.getItemData(this.advertisimenId, 'advertisiment').subscribe(
            (responce) => {
              console.log(responce);
              this.advertisiment.start_time = responce['ad'].start_time.split(' ').join("T");
              this.advertisiment.end_time = responce['ad'].end_time.split(' ').join("T");
              this.advertisiment.description = responce['ad'].description;
              this.advertisiment.description_en = responce['ad'].description_en;
              this.advertisiment.status = responce['ad'].status;
              this.urlImg = this.authSer.pathImg + responce['ad'].photo;
              this.spinner.hide();
            },
            (error) => {
              console.log(error);
            }
          );

        } else {
          console.log('Catch Error Go To Home !');
        }
      }
    ); 
  }



  onFileChanges(event) {
    this.checkChangePhoto = true;
    this.fileUpload = event[0];
    console.log(this.fileUpload);
  }

  getUrl(event) {   
    console.log(event);
    if (event.target.files && event.target.files[0]) {
      console.log(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'];
    }
    console.log(this.urlImg);
  }
 }

 onSubmitted() {
  
  if(this.checkChangePhoto) {
    this.formAdvertisimentData.value['photo'] = this.fileUpload.base64;
    this.formAdvertisimentData.value['photo_type'] = this.fileUpload.type.split('/')[1];
  }
  this.formAdvertisimentData.value['start_time'] = this.formAdvertisimentData.value['start_time'].split('T').join(" ");
  this.formAdvertisimentData.value['end_time'] = this.formAdvertisimentData.value['end_time'].split('T').join(" ");

   console.log(this.formAdvertisimentData.value);

   if(!this.typeMode) {
     //add logic

      if(!this.formAdvertisimentData.value['photo']) {
        this.toastr.warning('قم بإختيار صوره !');
      } else {
        this.dashboardSer.addItem(this.formAdvertisimentData.value, 'advertisiment').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم الإنشاء بنجاح ');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في الإنشاء');
          }
        )
      }
   } else {

    this.formAdvertisimentData.value['id'] = this.advertisimenId;
    console.log(this.formAdvertisimentData.value);

    if(this.checkChangePhoto){
      if(!this.formAdvertisimentData.value.photo) {
        this.toastr.warning('قم بإختيار صوره !');
      } else {
        this.dashboardSer.editItem(this.formAdvertisimentData.value, this.advertisimenId, 'advertisiment').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم التعديل بنجاح ');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في التعديل');
          }
        );
      }
    } else {
        this.dashboardSer.editItem(this.formAdvertisimentData.value, this.advertisimenId, 'advertisiment').subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم التعديل بنجاح ');
          this.location.back();
        },
        (error) => {
          console.log(error);
          this.toastr.error('خطأ في التعديل');
        }
      );
    }
   

   }

   

 }



}
