import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Student_infoservice} from './Student_info.service';
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators, ValidationErrors } from '@angular/forms';
import { ExtensionService } from 'src/app/services/fnd/extension.service';
import { DashboardContentModel2 } from 'src/app/models/builder/dashboard'; 
import { Student_infocardvariable } from './Student_info_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
import { CsvService } from 'src/app/services/csv.service';
import { TranslateService } from '@ngx-translate/core';
import { ThemeService } from 'src/app/services/theme.service';
import { Subscription } from 'rxjs';
import { ExcelService } from 'src/app/services/excel.service';
import * as moment from 'moment';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Student_info',
  templateUrl: './Student_info.component.html',
  styleUrls: ['./Student_info.component.scss']
})
export class Student_infoComponent implements OnInit {
  cardButton = Student_infocardvariable.cardButton;
  cardmodeldata = Student_infocardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Student_infocardvariable.cardButton;
  cardmodal;  changeView(){
  this.isCardview = !this.isCardview;
  }
    beforeText(fieldtext: string): string { // Extract the text before the first '<'
    const index = fieldtext.indexOf('<');
    return index !== -1 ? fieldtext.substring(0, index) : fieldtext;
  }
  afterText(fieldtext: string): string { // Extract the text after the last '>'
    const index = fieldtext.lastIndexOf('>');
    return index !== -1 ? fieldtext.substring(index + 1) : '';
  }
  transform(fieldtext: string): string {
    const match = fieldtext.match(/<([^>]*)>/);
    return match ? match[1] : ''; // Extract the text between '<' and '>'
  }
 userrole;
  rowSelected :any= {};
  modaldelete=false;
  modalEdit=false;
  modalAdd= false;
  public entryForm: FormGroup;
  loading = false;
  product;
  modalOpenedforNewLine = false;
  newLine:any;
 additionalFieldsFromBackend: any[] = [];
  formcode = 'Student_info_formCode'
tableName = 'Student_info';  checkFormCode; selected: any[] = [];
filterText: string = '';
  viewMode: 'table' | 'cards' = 'cards';
  private themeSubscription: Subscription; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Student_infoservice,
    private alertService: AlertService,
    private toastr: ToastrService,
private csvService: CsvService,
    private translate: TranslateService,
    private themeService: ThemeService, 
private excel: ExcelService,    private _fb: FormBuilder,
  ) { }

  switchLanguage(language: string) {
    this.translate.use(language);
  } 
  private editInterval: any;
// component button 
  ngOnInit(): void {
 this.themeSubscription = this.themeService.currentTheme$.subscribe(() => {
      // Theme changes will automatically update CSS variables
      // This triggers a re-render of themed elements
    });
    if(this.cardmodeldata !== ''){
     this.cardmodal = JSON.parse(this.cardmodeldata);
    this.dashboardArray = this.cardmodal.dashboard.slice();
    console.log(this.dashboardArray)
    }
    this.userrole=this.userInfoService.getRoles();
    this.getData();
    this.entryForm = this._fb.group({
student_name : [null],

address : [null],

phone_number: ['+91'],

email_field : [null,[Validators.required]],

password_field : [null],
confirmpassword_field : [null],

percentage_field : [null,[Validators.required]],

is_active : [true],

gender : [null],



distric : [null],

qrcode_field : [null],

currency : [null, { updateOn: 'blur' }],


 







    }, {
        validator: Confirmedpassword_fieldValidator('password_field', 'confirmpassword_field')















  }); // component_button200
 // form code start
    this.extensionService.getJsonObjectsByFormCodeList(this.formcode).subscribe(data => {
      console.log(data);
      const jsonArray = data.map((str) => JSON.parse(str));
      this.additionalFieldsFromBackend = jsonArray;
      this.checkFormCode = this.additionalFieldsFromBackend.some(field => field.formCode === "Student_info_formCode");
      console.log(this.checkFormCode);
      console.log(this.additionalFieldsFromBackend);
      if (this.additionalFieldsFromBackend && this.additionalFieldsFromBackend.length > 0) {
        this.additionalFieldsFromBackend.forEach(field => {
          if (field.formCode === this.formcode) {
            if (!this.entryForm.contains(field.extValue)) {
              // Add the control only if it doesn't exist in the form
              this.entryForm.addControl(field.extValue, this._fb.control(field.fieldValue));
            }
          }
        });
      }
    });
    console.log(this.entryForm.value);
    // form code end 

























  }
 ngOnDestroy(): void {
 if (this.themeSubscription) {
      this.themeSubscription.unsubscribe();
    }
    if (this.editInterval) {
      clearInterval(this.editInterval);
    }
  }
  get filteredGroups(): any[] {
    const items: any[] = (this.product as unknown as any[]) || [];
    const text = (this.filterText || '').toLowerCase();
    if (!text) { return items; }
    return items.filter(g => (
((g?.student_name || '').toString()).toLowerCase().includes(text) ||

((g?.address || '').toString()).toLowerCase().includes(text) ||

((g?.phone_number || '').toString()).toLowerCase().includes(text) ||

((g?.email_field || '').toString()).toLowerCase().includes(text) ||

((g?.password_field || '').toString()).toLowerCase().includes(text) ||

((g?.percentage_field || '').toString()).toLowerCase().includes(text) ||

((g?.is_active || '').toString()).toLowerCase().includes(text) ||

((g?.gender || '').toString()).toLowerCase().includes(text) ||

((g?.imageupload_field || '').toString()).toLowerCase().includes(text) ||

((g?.distric || '').toString()).toLowerCase().includes(text) ||

((g?.qrcode_field || '').toString()).toLowerCase().includes(text) ||

((g?.currency || '').toString()).toLowerCase().includes(text) 

    ));
  }

  setViewMode(mode: 'table' | 'cards') { this.viewMode = mode; }
  onExport() {
    this.excel.exportAsExcelFile(this.product, 'user_',
      moment().format('YYYYMMDD_HHmmss'))
  }















FileDataImageupload_field: any[];
  selectedImageupload_field: any[];







 error; 
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
this.product = [...this.product].reverse(); if(this.product.length==0){
        this.error="No Data Available"
     }   
    },(error) => {
      console.log(error);
      if(error){
       this.error="Server Error";
     }
    });
  }
  onEdit(row) {
    this.rowSelected = row;
















    this.selectedimageupload_field = [];
    this.mainService.uploadImageupload_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageupload_field = uploaddata;
    
    })








    this.modalEdit = true;
  }
   onDelete(row) {
    this.rowSelected = row;
     this.modaldelete=true;
  }
  delete(id)
  {
    this.modaldelete = false;
    console.log("in delete  "+id);
    this.mainService.delete(id).subscribe(
      (data) => {
        console.log(data);
        this.ngOnInit();
  if (data) {				      this.toastr.success('Deleted successfully');      }
    });
  }
    onUpdate(id) {
    this.modalEdit = false;
























    //console.log("in update");
    console.log("id  " + id);
    console.log(this.rowSelected);
    //console.log("out update");
    this.mainService.update(id, this.rowSelected).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Update Successfully");
        }
setTimeout(() => {
      this.ngOnInit();
    }, 500);
















for (let i = 0; i < this.selectedimageupload_field.length; i++){

  this.mainService.uploadImageupload_field(data.id,this.tableName,this.selectedimageupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}







      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("update Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Updated");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Updated");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  } 
onCreate() {
     this.modalAdd=false;
























  this.mainService.create(this.entryForm.value).subscribe(
    (data) => {
      console.log(data);
  if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
setTimeout(() => {
      this.ngOnInit();
    }, 500);















for (let i = 0; i < this.selectedimageupload_field.length; i++){

  this.mainService.uploadImageupload_field(data.id,this.tableName,this.selectedimageupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}








      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  goToAdd() {
this.modalAdd = true; this.submitted = false;















this.FileDataImageupload_field = [];
this.selectedImageupload_field =[];








  }
 submitted = false;
onSubmit() {
  console.log(this.entryForm.value);
 this.submitted = true;
  if (this.entryForm.invalid) {
    return;
  }this.onCreate();

} 


rsModaladdress = false;   
goToReplaceStringaddress(row){
this.rowSelected = row;     this.rsModaladdress  =true;   }

isValidPhone_number(phone: string): boolean {
  const phonePattern = /^(\+[1-9][0-9]{0,2})?[1-9][0-9]{9}$/;
  return phonePattern.test(phone);
}

isValidemail_field(email: string): boolean {
						 const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
						    return emailPattern.test(email);   }

newpHidepassword_field: boolean = true;
 newIconpassword_field: string = "eye"; 
newShapeChangerpassword_field() {
this.newpHidepassword_field = !this.newpHidepassword_field;  
 if(this.newpHidepassword_field){
this.newIconpassword_field = 'eye'   } else {     this.newIconpassword_field = 'eye-hide'   }
} 

 newaddpHidepassword_field: boolean = true;
 newaddIconpassword_field: string = "eye";
newaddChangerpassword_field() {   this.newaddpHidepassword_field = !this.newaddpHidepassword_field;
 if(this.newaddpHidepassword_field){     this.newaddIconpassword_field = 'eye'   } else {
  this.newaddIconpassword_field = 'eye-hide'   } }





updategender (gender : string): void {    
 this.entryForm.get('gender').setValue(gender);   }

updategenderEdit(gender : string): void {    this.rowSelected.gender  =  gender }
						 ;

filePreviewimageupload_field: string | ArrayBuffer | null = null;
FileDataimageupload_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedimageupload_field: File[]=[]; 
public onFileChangedimageupload_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDataimageupload_field[index].uploadedfile_name = files[i].name;
    this.selectedimageupload_field.push(files[i]);
    if (file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDataimageupload_field[index] = {
          ...this.FileDataimageupload_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesimageupload_field(){
      this.FileDataimageupload_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowimageupload_field(index,id) {
      this.FileDataimageupload_field.splice(index, 1);

      if(id){
      this.mainService.uploadImageupload_fielddelete(id).subscribe(data =>{
        console.log(data);
      })
      }
    }





//currency  field start
   formatCurrencycurrency () {
    // Format the currency with two decimal places    
	this.rowSelected.currency = Number(this.rowSelected.currency ).toFixed(2);
    // Remove commas from the formatted currency   
	 this.rowSelected.currency = this.rowSelected.currency?.replace(/,/g, '');  }
  //currency  field end


  // csv

  modalCsv = false;
  selectedFiles: File;
  fileList;
  ttype = 'usergroupmaintenance';


  // Import CSV
  public selectFile(event) {
    this.selectedFiles = event.target.files[0];
    // this.saveCsv();
  }

  csvImport() {
    console.log("import CSV");
    this.modalCsv = true;
  }
  saveCsv() {
    this.csvService.importCsv(this.selectedFiles, this.ttype).subscribe(data => {
      console.log(data);
      this.fileList = data;
      this.modalCsv = false;
    },
      (error) => {
        console.log(error);
        if (error.status == 202) {
          this.toastr.success(error.error.text)
        }
      });
  }

  downloadFiles() {
    this.csvService.downloadCsvs(this.ttype);

  }
// updateaction
}







export function Confirmedpassword_fieldValidator(controlName: string, matchingControlName: string){
  return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];
      if (matchingControl.errors && !matchingControl.errors.confirmedpassword_fieldValidator) {
          return;
      }
      if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ confirmedpassword_fieldValidator: true });
      } else {
          matchingControl.setErrors(null);
      }
  }
}
















