import { Component, OnInit, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { IgenMenuDto } from 'src/app/_dto/igenMenu.dto';
import { MenuFormatDto } from 'src/app/_dto/menu-format.dto';
import { apiUrl } from 'src/app/_providers/_resources/api-url.properties';
import { AuthService } from 'src/app/_providers/_services/auth.service';
import { MenuService } from 'src/app/_providers/_services/menu.service';
import { UiService } from 'src/app/_providers/_services/ui.service';
import { EmailService } from 'src/app/pages/auth/services';
import { Observable, of } from 'rxjs';
import { Email, User } from 'src/app/pages/auth/models';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { routes } from 'src/app/consts';
import { MasterService } from 'src/app/_providers/_services/master.service';
import { TenderDetailDto } from 'src/app/_dto/tender-detail.dto';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { DatePipe } from '@angular/common';
import { MatDialog } from '@angular/material/dialog';
import { CommonDto } from 'src/app/_dto/common.dto';
import { error } from 'console';
import Swal from 'sweetalert2';
import { ThemePalette } from '@angular/material/core';
import { GalleryDto } from 'src/app/_dto/gallery.dto';
import { subGalleryDto } from 'src/app/_dto/sub-gallery.dto';
import { ProgressSpinnerMode } from '@angular/material/progress-spinner';


@Component({
  selector: 'app-gallery',
  templateUrl: './gallery.component.html',
  styleUrls: ['./gallery.component.scss']
})
export class GalleryComponent implements OnInit {
  @Input() isMenuOpened: boolean;

  @Output() isShowSidebar = new EventEmitter<boolean>();

  public user$: Observable<User>

  public emails$: Observable<Email[]>

  public routers: typeof routes = routes;


  seculevel: string = ''

  dataSource: MatTableDataSource<GalleryDto>;

  displayedColumns: any = ['actions', 'slno', 'category', 'title', 'description'];

  // displayedColumns:any = ['actions','slno','tenderCategory','status'];

  dataCopy: any;

  pageLength: any;

  searchTerm: any;

  newDate = new Date();

  enableDownload: boolean = true

  amountPaid: boolean = false;

  @ViewChild('paginator') paginator: MatPaginator;

  @ViewChild(MatSort, { static: false }) sort: MatSort;

  noData: boolean;

  userId: string;

  tenderId: number;

  countStatusP: any;

  dialogRef: any;

  galleryData: GalleryDto[];

  selectedGallery: GalleryDto;

  color: ThemePalette = 'primary';

  isEdit: boolean = false;

  subImages: any[] = [];


  projectTypeLov = [
    { project: "Architecture Design", value: 'AD' },
    { project: "Interior Design", value: 'ID' },
    { project: "Project Management", value: 'PM' }
  ]

  categoryLov = [
    { category: "Residential", value: 'residential' },
    { category: "Commercial", value: 'Commercial' }
  ]
  imageUrl: any

  spinColor: ThemePalette = 'warn';
  mode: ProgressSpinnerMode = 'indeterminate';
  value = 50;
  spinLoading:boolean=false;

  constructor(
    private _menuService: MenuService,
    private router: Router,
    private _ui: UiService,
    private emailService: EmailService,
    private authenticationService: AuthService,
    private _masterService: MasterService,
    private errorService: ErrorTranslateService,
    private datePipe: DatePipe,
    private route: ActivatedRoute,
    private dialog: MatDialog
  ) {
    // this.user$ = this.getUser();
    this.seculevel = localStorage.getItem('seculevel')
    // console.log('=====level====',this.seculevel);
    this.userId = localStorage.getItem('userId');
    this.tenderId = +this.route.snapshot.paramMap.get('id');

    // this.emails$ = this.emailService.loadEmails();
    // this.getSchoolLogo();

  }


  // displayedColumns: string[] = ['no', 'name','download'];


  loading: boolean = true;
  menuData: any;
  model: any;


  async ngOnInit() {

    this.enableDownload = true;
    this.galleryData = []
    this.getData();

  }



  getData() {

    this._masterService.getMasterData(apiUrl.gallery).then((res) => {
      this.galleryData = res;
      this.dataCopy = res;
      this.pageLength = this.galleryData.length;
      this.dataSource = new MatTableDataSource(this.galleryData);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      this.noData = (this.galleryData && this.galleryData.length == 0) ? true : false;
      this.loading = false;
    }, err => {
      console.error(err)
    })




  }



  convertDateFormat(dateString: string): string {
    const date = new Date(dateString);
    return this.datePipe.transform(date, 'yyyy-MM-ddTHH:mm');
  }

  getGalleryById(id) {
    this._masterService.getMasterDatabyId(apiUrl.gallery, id).then(res => {
      this.selectedGallery = res
    }, err => {
      console.log(err);

    })
  }

  editCategoryDialog(templateRef, id) {
    this.selectedGallery = new GalleryDto();
    this.isEdit = true;
    this.dialogRef = this.dialog.open(templateRef, {
      width: '600px',
      maxHeight: '60vh',
      minHeight: '60vh',
      disableClose: true
    });
    this.getGalleryById(id);
  }

  openCategoryDialog(templateRef) {
    this.isEdit = false;
    this.selectedGallery = new GalleryDto();
    this.selectedGallery.subGallery = [];
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      maxHeight: '80vh',
      // minHeight: '60vh',
      disableClose: true
    });
  }
  closeDialog() {
    this.selectedGallery = new GalleryDto();

    this.dialogRef.close();
    // this.getData()
  }

  sortData(sort: Sort) {
    const data = this.galleryData.slice();
    if (!sort.active || sort.direction === '') {
      this.dataSource.data = data;

      return;
    }

    this.dataSource.data = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'category':
          return compare(a.category, b.category, isAsc);
        case 'title':
          return compare(a.title, b.title, isAsc);
        case 'description':
          return compare(a.description, b.description, isAsc);
        case 'projectType':
          return compare(a.projectType, b.projectType, isAsc);
        default:
          return 0;
      }
    });
  }

  search() {
    this.galleryData = this.dataCopy;
    this.loading = true;
    if (!this.searchTerm || this.searchTerm == null || this.searchTerm == undefined || this.searchTerm == "") {
      this._ui.toastMessage(this.errorService.translate('enterSearchTerm'), 3000);
      this.getData();
      return;
    }
    this.galleryData = this.galleryData.filter(res => {
      let includedInCategory = (res.category) ? res.category.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedIntitle = (res.title) ? res.title.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedIndescription = (res.description) ? res.description.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInprojectType = (res.projectType) ? res.projectType.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;

      if (includedInCategory || includedIntitle || includedIndescription || includedInprojectType)
        return true;
      else
        return false;
    });
    this.noData = (this.galleryData && this.galleryData.length == 0) ? true : false;
    this.pageLength = this.galleryData.length;
    this.dataSource = new MatTableDataSource(this.galleryData);
    this.loading = false;
  }

  reset() {
    this.searchTerm = "";
    this.getData();
  }

  pushSubImages() {
    let temp = new subGalleryDto();
    this.selectedGallery.subGallery.push(temp)
  }

  removeSubImage(i,image) {
    if(image && image.imageUrl && image.imageUrl != ''){
      this._masterService.deleteMasterData(apiUrl.subGalleryImg+`/${this.selectedGallery.id}`,image.imageUrl).then(res=>{
        this._ui.toastMessage(res['message'])
      },err=>{
        this._ui.toastMessage(err.error.message)

      })
    }
    this.selectedGallery.subGallery.splice(i, 1);
  }

  downloadMainImage(mainImageURL){
    this.imageUrl=mainImageURL;
    this.spinLoading=true;
    // this._masterService.getMasterDatabyId(apiUrl.galleryImage,`${this.imageUrl}`).then(res=>{
    //   console.log('downloading . . .')
    // })
    this._masterService.downloadFileWithAuth(apiUrl.galleryImage,`${this.imageUrl}`).then(res=>{
      this.spinLoading=false;
    })

  }


  downloadSubImage(mainImageURL,i){
    this.imageUrl=mainImageURL;
    this.selectedGallery.subGallery[i].spinLoading=true;
    // this._masterService.getMasterDatabyId(apiUrl.galleryImage,`${this.imageUrl}`).then(res=>{
  
    // })
    this._masterService.downloadFileWithAuth(apiUrl.galleryImage,`${this.imageUrl}`).then(res=>{
     
      this.selectedGallery.subGallery[i].spinLoading=false;
    })

  }

  // downloadImage(i,image){
  //   console.log('image',image)
  //   if(image && image.imageUrl && image.imageUrl != ''){
  //   this._masterService.getMasterData(apiUrl.galleryImage,)
  //   }
  // }

  isImage(file: File): boolean {
    const allowedImageExtensions = ['jpg', 'jpeg', 'png'];
    const extension = file.name.split('.').pop()?.toLowerCase() || '';
    return allowedImageExtensions.includes(extension);
  }

  UploadMainImage(event) {

    
      if(!this.selectedGallery.projectType || this.selectedGallery.projectType == ''){
        this._ui.toastMessage('Select Project Type');
        return
      }
      if(!this.selectedGallery.category || this.selectedGallery.category == ''){
        this._ui.toastMessage('Select Category');
        return
      }
      if(!this.selectedGallery.title || this.selectedGallery.title == ''){
        this._ui.toastMessage('Add Title');
        return
      }
      if(!this.selectedGallery.description || this.selectedGallery.description == ''){
        this._ui.toastMessage('Add Description');
        return
      }

    const file = event.target.files[0];
    if (this.isImage(file)) {
      const fd = new FormData();
      fd.append('file', file);
      this._masterService.saveMasterData(apiUrl.picture,fd).then(res=>{ 
        this.selectedGallery.imageUrl = res.fileName;
        if(!this.selectedGallery.id || this.selectedGallery.id == null){
          this.tempSave();
        }
      })
    }
    else {
      this._ui.toastMessage(`Please attach an image file with extention - jpg,jpeg,png`)
    }

  }

  UploadSubImage(event,i) {

    const file = event.target.files[0];
    if (this.isImage(file)) {
      const fd = new FormData();
      fd.append('file', file);
      this._masterService.saveMasterData(apiUrl.picture,fd).then(res=>{
        this.selectedGallery.subGallery[i].imageUrl = res.fileName;
        this.selectedGallery.subGallery[i].galleryId = this.selectedGallery.id;
      })
    }
    else {
      this._ui.toastMessage(`Please attach an image file with extention - jpg, jpeg, png`)
    }

  }

  goToDashboard() {
    this.navigateTo(`analyst/dashboard`)
  }
  public openMenu(): void {
    this.isMenuOpened = !this.isMenuOpened;

    this.isShowSidebar.emit(this.isMenuOpened);
  }

  public signOut(): void {

    this.authenticationService.logOut();

  }

  
  signIn() {
    this.router.navigate(['/login']);
  }




  navigateTo(destination: any) {
    this.router.navigate([destination])
  }

tempSave(){
  this._masterService.saveMasterData(apiUrl.gallery, this.selectedGallery).then(res => {

    this.selectedGallery.id = res.id
  })
}

  saveGallery() {
    // if (!this.preSave()) {
    //   return;
    // }
    if(!this.selectedGallery.imageUrl || this.selectedGallery.imageUrl == ''){
      this._ui.toastMessage('Please add Image');
      return
    }
    if(!this.selectedGallery.subGallery || this.selectedGallery.subGallery.length<1){
      this._ui.toastMessage('Please add Additional Images');
      return
    }

    this._masterService.saveMasterData(apiUrl.gallery, this.selectedGallery).then(res => {
      this._ui.toastMessage(this.errorService.translate('saveSuccess'));
      this.selectedGallery = new GalleryDto();
      this.closeDialog();
      this.getData();
    },err=>{
      this._ui.toastMessage(err.error.message);

    })



  }
  editGallery() {
    if (!this.selectedGallery.category || this.selectedGallery.category == '') {
      this._ui.toastMessage(this.errorService.translate('categoryNameCannotBeBlank'));
      return;
    }
    this._masterService.updateMasterData(apiUrl.gallery, this.selectedGallery, this.selectedGallery.id).then(res => {
      this._ui.toastMessage(this.errorService.translate('categorySaved'));
      this.closeDialog();
      this.getData();
      this.selectedGallery = new GalleryDto();
      this.isEdit = false;
    }, err => {
      console.log(err);
      this._ui.toastMessage(err.error.message);

    })
  }


  deleteGallery() {
    this._masterService.deleteMasterData(apiUrl.gallery, this.selectedGallery.id).then(res => {
      this._ui.toastMessage(this.errorService.translate('deleteSuccess'));
      this.selectedGallery = new GalleryDto();
      this.closeDialog();
      this.getData();
    }, err => {
      console.log(err);
      this._ui.toastMessage(err.error.message);

    })
  }
}
function compare(a: any, b: any, isAsc: boolean): number {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
