import { HttpClient } from '@angular/common/http';
import { DashboardService } from './../../../shared/dashboard.service';
import { MainMenuService } from './../../../shared/main-menu.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
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-menu',
  templateUrl: './add-menu.component.html',
  styleUrls: ['./add-menu.component.css']
})
export class AddMenuComponent 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;
  servicesName:string = '';
  typeLink: string = '';
  menuId: number;
  serviceId: number;
  parentList = [];

  internalPages = [];

  menu = {
    name: '',
    name_en: '',
    parent_id: '',
    link: '',
    link2: '',
    status: '',
    ranking: '',
    link_type: '',
  };

  linkTypeCahnge: string = '';



  constructor(private toastr: ToastrService, 
    private spinner: NgxSpinnerService,
    private location: Location,
    private route: ActivatedRoute,
    private authSer: AuthServiceService,
    private authService: AuthServiceService,
    private dashBoardService: DashboardService,
    private http: HttpClient,
    private menuService: MainMenuService, ) { 
      this.spinner.show();
    }

  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.menu.status = '1';

    this.route.parent.params.subscribe(
      (params: Params) => {
        this.serviceId = params['serviceID'];
        if(this.serviceId == 6) {
          this.servicesName = 'خدمه إداره المحتوي';
        } else if(this.serviceId == 2) {
          this.servicesName = 'خدمه أدراه الصفحه الخارجيه';
        }
      }
    );

    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeMenuMode'] == 'edit') {
          this.typeMode = true;
          this.typeLink = 'تعديل';
          this.menuId = params['editMenuId'];
          this.dashBoardService.getItemData(this.menuId, 'mainMenu').subscribe(
            (responce) => {
              console.log(responce);
              console.log(responce['menu']);
              this.menu.name = responce['menu'].name;
              this.menu.name_en = responce['menu'].name_en;
              this.menu.link = responce['menu'].link;
              this.menu.status = responce['menu'].status;
              this.menu.ranking = responce['menu'].ranking;
              this.menu.parent_id = responce['menu'].parent_id ? responce['menu'].parent_id : '';
              this.menu.link_type = responce['menu'].link_type;
              this.menu.link = responce['menu'].link ? responce['menu'].link : '';
              this.menu.link2 = responce['menu'].link2 ? responce['menu'].link2 : '';  
              if(responce['menu'].photo) {
                this.checkValidImg = false;
                this.urlImg = this.authService.pathImg + responce['menu'].photo;
              }
              this.spinner.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        } else {
          this.typeLink = 'أنشاء جديد';
          this.spinner.hide();
        }
      }
    );


    //get external pages 
    this.http.get(this.authSer.pathApi + '/system_pages_list').subscribe(
      (responce) => {
        console.log('external pagesssssssssssssssss' , responce);
        this.internalPages = responce['pages'];
      }
    )

    this.menuService.getParentList().subscribe(
      (responce) => {
        console.log('parents' , responce);
        this.parentList = responce['menus'];
      }, 
      (error) => {
        console.log(error);
      }
    );

  };



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

 linkTypeValue(linkTypeVal) {
   console.log(linkTypeVal);
  this.menu.link_type = linkTypeVal.target.value;
 }

 //on submitted
 onSubmitted() {
   this.checkSaveClick = true;//to make save disabled after one click
  const formData = this.externalFormData.value;
  console.log(formData);
  if(this.checkChangeImage){
    formData['photo'] = this.imageBase64;
    formData['photo_type'] = this.photoType[1].toLowerCase();
  } 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(formData.photo_type != 'png' && this.photoEdit == true){
      this.toastr.warning('الصوره يجب أن تكون بصيغه png');
      this.checkSaveClick = false;
    } else {
      if(this.serviceId == 6) {
        this.dashBoardService.editItem( this.menuId, formData, 'internalMenu').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت التعديل بنجاح');
            this.location.back();
            this.checkSaveClick = false;
          },
          (error) => {
            this.checkSaveClick = false;
            console.log(error);
            this.toastr.error('خطأ في التعديل !');
          }
        );
      } else if(this.serviceId == 2) {
        this.dashBoardService.editItem( this.menuId, formData, 'externalMenu').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت التعديل بنجاح');
            this.location.back();
            this.checkSaveClick = false;
          },
          (error) => {
            this.checkSaveClick = false;
            console.log(error);
            this.toastr.error('خطأ في التعديل !');
          }
        );
      }
    }
  } else {
    if(this.imageBase64 == ''){
      this.toastr.warning('قم باختيار صوره !');
      this.checkSaveClick = false;
    } else if(formData.photo_type != 'png'){
      this.toastr.warning('الصوره يجب أن تكون بصيغه png');
      this.checkSaveClick = false;
    } else {
      if(this.serviceId == 6){
        this.dashBoardService.addItem(formData, 'internalMainMenu').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت الاضافه بنجاح');
            this.location.back();
            this.checkSaveClick = false;
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
            this.toastr.error('خطأ في الحفظ !');
          }
        );
      } else if(this.serviceId == 2){
        this.dashBoardService.addItem(formData, 'externalMainMenu').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تمت الاضافه بنجاح');
            this.location.back();
            this.checkSaveClick = false;
          },
          (error) => {
            console.log(error);
            this.checkSaveClick = false;
            this.toastr.error('خطأ في الحفظ !');
          }
        );
      }
    }
  }
 }

}
