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

@Component({
  selector: 'app-add-tab',
  templateUrl: './add-tab.component.html',
  styleUrls: ['./add-tab.component.css']
})

export class AddTabComponent implements OnInit {

  @ViewChild('f') formTabData: NgForm;

  typeMode: boolean = false;
  checkSaveclick:boolean = false;

  eventId: number;
  tabId: number;
  typeLink: string = '';
  checkFileChange: boolean = false;
  fileData: any;
  checkShowDownloadFile: boolean = false;
  nameLink = "";

  tab = {
    name: '',
    name_en: '',
    ranking: '',
    type: '',
    status: '',
    file: '',
  }
  

  constructor(private tabService: TabsService,
    private userService: UserService,
    private location: Location,
    private authSer: AuthServiceService,
    private toastr: ToastrService,
    private route: ActivatedRoute, 
    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.internalHeader = false;
    this.tab.status = "1";
    
    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeTabMode'] == 'edit') {
          this.spineer.show();
          this.typeMode = true;
          this.typeLink = 'تعديل';
          this.tabId = params['editTabId'];
          this.tabService.getTabData(this.tabId).subscribe(
            (responce) => {
              console.log(responce);
              const tabData = responce['tab'];
              console.log(tabData);
              this.tab.name = tabData.name;
              this.tab.name_en = tabData.name_en;
              this.tab.ranking = tabData.ranking;
              this.tab.type = tabData.type;
              this.tab.status = tabData.status;
              this.tab.file = tabData.file;
              responce['tab'].file ? this.checkShowDownloadFile = true : this.checkShowDownloadFile = false;
              this.spineer.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        } else {
          this.typeLink = 'إنشاء جديد';
        }
      }
    );
  }


  onFileChanges(event) {

    console.log(event);
    this.nameLink = event[0].name;
    // this.imageBase64 = event[0].base64;
    // this.photoType = event[0].type.split('/');
    this.fileData = {
      file: event[0].base64,
      file_type: event[0].type.split('/')[1],
    };

    this.checkFileChange = true;

    console.log(this.fileData);
    this.checkShowDownloadFile = 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'];
    }
  }
 }



  //on submitted form
  onSubmitted() {

    this.checkSaveclick = true;

    if(this.checkFileChange) {
      this.formTabData.value['file'] = this.fileData.file;
      this.formTabData.value['file_type'] = this.fileData.file_type;
    }

    console.log(this.formTabData.value);

    if(this.typeMode) {
      if(this.checkFileChange){
        if(this.formTabData.value['file']){
          this.tabService.editEvent(this.formTabData.value, this.tabId).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم التعديل بنجاح');
              this.location.back();
              this.checkSaveclick = false;
            },
            (error) => {
              console.log(error);
              this.toastr.error('خطأ في التعديل ');
              this.checkSaveclick = false;
            }
          );
        } else {
          this.toastr.warning('قم برفع ملف !')
        }
      } else {
        this.tabService.editEvent(this.formTabData.value, this.tabId).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم التعديل بنجاح');
            this.location.back();
            this.checkSaveclick = false;
          },
          (error) => {
            console.log(error);
            this.toastr.error('خطأ في التعديل ');
            this.checkSaveclick = false;
          }
        );
      }
     
    } else {
      this.tabService.addTab(this.formTabData.value).subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم الاضافه بنجاح');
          this.location.back();
          this.checkSaveclick = false;
        },
        (error) => {
          console.log(error);
          this.toastr.error('خطأ في الأضافه ');
          this.checkSaveclick = false;
        }
      );
    }
    
  };

 

}
