import { DashboardService } from './../../../shared/dashboard.service';
import { HttpClient } from '@angular/common/http';
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;
  checkValidImg: boolean = true;
  imageBase64: string = '';
  imageMainBase64:string = '';
  photoType: string = '';
  typeLink: string = '';
  checkSaveClick: boolean = false;
  photoEdit:boolean = false;
  checkAddMode: boolean = false;
  serviceName: string = '';
  mainPhotoDefault: string = '../../../../assets/image/Group 408.png';
  mainPhotoPath: string = '';
  serviceId: number;
  

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

  images = [{
    base64: '',
    photoType: '',
    urlImg: '../../../../assets/image/Group 408.png',
    id: '',
    is_main_photo: 0
  }];

  //add more div photo
  plusImage() {
    this.checkAddMode = true;
    this.images.push({
     base64: '',
     photoType: '',
     urlImg: '../../../../assets/image/Group 408.png',
     id: '',
     is_main_photo: 0
    });
  }




  constructor(private newService: NewService,
    private userService: UserService,
    private authSer: AuthServiceService,
    private location: Location,
    private toastr: ToastrService,
    private route: ActivatedRoute,
    private http: HttpClient, 
    private authService: AuthServiceService,
    private dashBoardService: DashboardService,
    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.new.status = '1';

    this.route.parent.params.subscribe(
      (params: Params) => {
        this.serviceId = params['serviceID'];
        if(this.serviceId == 13) {
          this.serviceName = 'خدمه إداره المحتوي';
        } else if(this.serviceId == 2) {
          this.serviceName = ' خدمه إداره الصفحه الخارجيه';
        }
      }
    )
    
    this.route.params.subscribe(
      (params: Params) => {
        if(params['typeNewMode'] == 'edit') {
          this.typeLink = 'تعديل';
          this.images = [];
          this.spineer.show();
          this.typeMode = true;
          this.newId = params['editNewId'];
          this.dashBoardService.getItemData(this.newId, 'news').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'].photos) {
                this.checkValidImg = false;
                for(let i = 0 ; i < newData.photos.length; i++) { 
                  this.images.push({
                    base64: '',//this.onFileChanges(newData.photos[i].photo,i),
                    photoType: '',
                    urlImg : this.authSer.pathImg +  newData.photos[i].photo,
                    id: newData.photos[i].id,
                    is_main_photo : newData.photos[i].is_main_photo,
                  });
                  console.log('imageeeees' , this.images);
                }
              }
              this.spineer.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        } else {
          this.typeLink = 'إنشاء جديد';
        }
      }
    );
  }



  onFileChanges(event,index) {
    console.log(event);
    console.log('upload image index' , index);
    let dateEditUplad = {};

    if(this.typeMode) {
      if(this.checkAddMode) {
        dateEditUplad = {
          'photo': event[0].base64,
          'photo_type': event[0].type.split('/')[1],
          'report_id':  this.newId,
        }
      } else {
        dateEditUplad = {
          'photo': event[0].base64,
          'photo_type': event[0].type.split('/')[1],
          'photo_id':  this.images[index].id,
        }
      }

      console.log(dateEditUplad);
      this.http.post(this.authSer.pathApi + '/upload_report_photo', dateEditUplad).subscribe(
        (responce) => {
          console.log(responce);
        },
        (error) => {
          console.log(error);
        }
      )
    } else {
      this.imageBase64 = event[0].base64;
      this.images[index].base64 = this.imageBase64;
      this.photoType = event[0].type.split('/');
      this.images[index].photoType = this.photoType[1];
      console.log('images array' , this.images);
      this.checkValidImg = false;
    }
  }

  getUrl(event,index) {   
    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'];
      this.images[index].urlImg = event.target['result'];
    }
  }
 }

 deleteImg(index, data) {
   if(this.typeMode) {
    this.images.splice(index , 1);
    this.http.get(this.authSer.pathApi + '/delete_report_photo/' + data.id).subscribe(
      (responce) => {
        console.log(responce);
      },
      (error) => {
        console.log(error);
      }
    );
   } else {
     this.images.splice(index,1);
   }
 
 }


 deleteMainImg() {
   this.mainPhotoPath = '';
 }



  //submitted form
  onSubmitted() {

    this.checkSaveClick = true;

    const formData = this.newForm.value;
      
    if(this.typeMode){
        //to remove photo from object not has edit on it
        // const images = [];
        // for(let i = 0; i < this.images.length; i++) {
        //   if(this.images[i].base64 == '') {
        //     this.images.splice(this.images.indexOf(this.images[i]) , 1);
        //   } else {
        //     if(i == 0) {
        //       images.push({
        //         photo: this.images[i].base64,
        //         photo_type: this.images[i].photoType,
        //       });
        //     } else {
        //       images.push({
        //         photo: this.images[i].base64,
        //         photo_type: this.images[i].photoType,
        //       });
        //     }
        //   }
        // }

        //formData['images'] = images;

        console.log(formData);

        if(this.serviceId == 2) {
          this.dashBoardService.editItem(this.newId, formData,'externalNew').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تمت التعديل بنجاح');
              this.location.back();
            },
            (error) => {
              console.log(error);
              this.toastr.error('خطأ في التعديل !');
              this.checkSaveClick = false;
            }
          );
        } else if(this.serviceId == 6){
          this.dashBoardService.editItem(this.newId, formData, 'internalNew').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تمت التعديل بنجاح');
              this.location.back();
            },
            (error) => {
              console.log(error);
              this.checkSaveClick = false;
              this.toastr.error('خطأ في التعديل !');
            }
          );
        }
    
    } else {
      if(this.images[0].base64 == ''){
        this.toastr.warning('قم باختيار الصوره الرئيسيه !');
        this.checkSaveClick = false;
      } else {

        const images = [];

        for(let i = 0; i < this.images.length; i++) {
          if(i == 0) {
            images.push({
              photo: this.images[i].base64,
              photo_type: this.images[i].photoType,
              is_main_photo: 1,
            });
          } else {
            images.push({
              photo: this.images[i].base64,
              photo_type: this.images[i].photoType,
              is_main_photo: 0,
            });
          }
        }

        formData['images'] = images;

        console.log(formData);

        if(this.serviceId == 6) {
          this.dashBoardService.addItem(formData, 'internalNews').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 if(this.serviceId == 2) {
          this.dashBoardService.addItem(formData, 'externalNews').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تمت الاضافه بنجاح');
              this.location.back();
            },
            (error) => {
              console.log(error);
              this.toastr.error('خطأ في الحفظ !');
              this.checkSaveClick = false;
            }
          );
        }

     

      }
    }
  }

}
