import { Component, OnInit, EventEmitter, Input, Output, ViewChild, ElementRef } 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 { ChangeDetectorRef } from '@angular/core';
import { UserDto } from 'src/app/_dto/user.dto';
import { ThemePalette } from '@angular/material/core';
@Component({
  selector: 'app-user-management',
  templateUrl: './user-management.component.html',
  styleUrls: ['./user-management.component.scss']
})
export class UserManagementComponent implements OnInit {
  @Input() isMenuOpened: boolean;

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

  public user$: Observable<User>

  public emails$: Observable<Email[]>

  public routers: typeof routes = routes;

  schoolLogoPath: string;


  seculevel: string = ''

  dataSource: MatTableDataSource<UserDto>;

  displayedColumns: any = ['actions', 'slno', 'userName', 'email', 'secuLevel', 'active'];

  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;

  @ViewChild("toggleEmployee") employeeRef: ElementRef;

  noData: boolean;

  userId: string;

  tenderId: number;

  countStatusP: any;

  dialogRef: any;

  userData: UserDto[];

  selectedUser: UserDto;

  color: ThemePalette = 'primary';

  isEdit: boolean = false;

  userLov : any;

  desc: boolean=false;
  changeToUser: 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,
    private cdr: ChangeDetectorRef
  ) {
    // this.user$ = this.getUser();
    this.seculevel = localStorage.getItem('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;

  isOpened:boolean = false;


  async ngOnInit() {
    this.selectedUser = new UserDto(); 

    this.enableDownload = true;
    this.userData = []
    this.getData();
    this.userLov = [
      {label: 'User',value:'User',desc:'Users can engage in the tender process by submitting the required fees.'},
      {label: 'Analyst',value:'Analyst',desc:'Analysts have the authority to create new tenders within this application.'},
      {label: 'User',value:'User',desc:'Users can engage in the tender process by submitting the required fees.'}

    ]

  }



  getData() {

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




  }


  event(event){

     
    if(event.value ){
      this.desc =true 

    }else {
      this.desc = false;
    }
  }

  triggerEvent(event,selectedUser){
    if(selectedUser.secuLevel == 'SuperAdmin'){ 
      this._ui.toastMessage('Super admin cannot be changed to a user');
      this.employeeRef['_checked'] = true
      selectedUser.employee=true;     
    }
    else if(selectedUser.secuLevel !=='User' &&  selectedUser.employee==false){ 

      this._ui.toastMessage('Only users have the privilage to switch  Employee to a User.');
      this.employeeRef['_checked'] = true
      selectedUser.employee=true;    
    } 

    this.isOpened = event
    this.cdr.detectChanges();
    if(!event)
    setTimeout(() => {
      this.isOpened = false
    }, 1000); // Mark for check
  }

  regular(){
      if(!this.isOpened){
        this.isOpened = false
      }
  }

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

  getUserById(id) {
    this._masterService.getMasterDatabyId(apiUrl.userData, id).then(res => {
      this.selectedUser = res;

    }, err => {
      console.log(err);

    })
  }

  editUserDialog(element,templateRef, id) {
   

    this.selectedUser = new UserDto();
    this.isEdit = true;

    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false
      
    });
    this.getUserById(id);

   
  }

  toggleChange(selectedUser: any) {
    if (selectedUser.secuLevel == 'SuperAdmin'){ 
      this._ui.toastMessage('Super admin cannot be changed to a user');
      this.employeeRef['_checked'] = true
      selectedUser.employee=true;     
    
  }
   else if (selectedUser.secuLevel !== 'User') {
      this._ui.toastMessage('To change an employee into a user, you must first update their role to "user"');
      this.employeeRef['_checked'] = true
      this.selectedUser.employee = true; 
      
    }
  }




  openCategoryDialog(templateRef) {
    this.isEdit = false;
    this.selectedUser = new UserDto();
    this.dialogRef = this.dialog.open(templateRef, {
      width: '500px',
      disableClose: false
    });
    this.selectedUser.active = true
  }
  closeDialog() {
    this.dialogRef.close();
  }

  sortData(sort: Sort) {
    const data = this.userData.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 'userName':
          return compare(a.userName, b.userName, isAsc);
        case 'email':
          return compare(a.email, b.email, isAsc);
        case 'secuLevel':
          return compare(a.secuLevel, b.secuLevel, isAsc);
        case 'active':
          return compare(a.active, b.active, isAsc);
        default:
          return 0;
      }
    });
  }

  search() {
    this.userData = 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.userData = this.userData.filter(res => {
      let includedInUserName = (res.userName) ? res.userName.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInEmail = (res.email) ? res.email.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInSecuLevel = (res.secuLevel) ? res.secuLevel.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;


       


      if (includedInUserName || includedInEmail || includedInSecuLevel )
        return true;
      else
        return false;
    });
    this.noData = (this.userData && this.userData.length == 0) ? true : false;
    this.pageLength = this.userData.length;
    this.dataSource = new MatTableDataSource(this.userData);
    this.loading = false;
  }

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


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

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

  public signOut(): void {

    this.authenticationService.logOut();

  }

  paymentCheck() {
    this._masterService.getMasterDatabyId(apiUrl.paymentCheck, `${this.userId}/${this.tenderId}`).then(res => {


      if (res.length > 0 && res[0].transId && res[0].transId != null && res[0].transId != undefined) {
        this.amountPaid = true
      }

    })
  }

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




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



  saveUser() {
    if (!this.selectedUser.category || this.selectedUser.category == '') {
      this._ui.toastMessage(this.errorService.translate('categoryNameCannotBeBlank'));
      return;
    }
    this._masterService.saveMasterData(apiUrl.userData, this.selectedUser).then(res => {
      this._ui.toastMessage(this.errorService.translate('categorySaved'));
      this.closeDialog();
      this.getData();
      this.selectedUser = new UserDto();
    })



  }
  editUser() {
  
    this._masterService.updateMasterData(apiUrl.userData, this.selectedUser, this.selectedUser.userId).then(res => {
      this._ui.toastMessage(this.errorService.translate('updateSuccess'));
      this.closeDialog();
      this.getData();
      this.selectedUser = new UserDto();
      this.isEdit = false;
    }, err => {
      console.log(err);

    })
  }


  deleteUser() {
    this._masterService.deleteMasterData(apiUrl.userData, this.selectedUser.userId).then(res => {
      this._ui.toastMessage(this.errorService.translate('deleteSuccess'));
      this.closeDialog();
      this.getData();
      this.selectedUser = new UserDto();
    }, err => {
      console.log(err);

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