import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Basicp3service} from './Basicp3.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 { Basicp3cardvariable } from './Basicp3_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-Basicp3',
  templateUrl: './Basicp3.component.html',
  styleUrls: ['./Basicp3.component.scss']
})
export class Basicp3Component implements OnInit {
  cardButton = Basicp3cardvariable.cardButton;
  cardmodeldata = Basicp3cardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Basicp3cardvariable.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 = 'Basicp3_formCode'
tableName = 'Basicp3';  checkFormCode; selected: any[] = [];
filterText: string = '';
  viewMode: 'table' | 'cards' = 'cards';
  private themeSubscription: Subscription; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Basicp3service,
    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({
toggle_switch : [true],

toggle_switch2 : [true],

url_field : [null],

url_field2 : [null],

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

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

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

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

documentsequenc : [null],

recaptcha : ['', [Validators.required,this.checkrecaptcha.bind(this)]],

recaptcha2 : ['', [Validators.required,this.checkrecaptcha2.bind(this)]],


 





















  }); // 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 === "Basicp3_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 


















this.generaterecaptcha()

this.generaterecaptcha2()


  }
 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?.toggle_switch || '').toString()).toLowerCase().includes(text) ||

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

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

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

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

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

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

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

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

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

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

    ));
  }

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





















 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.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);






















      }, (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);






















      }, (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;






















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

} 




isValidurl_field(url: string): boolean {
						    return  /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(url);   } 
						goTourl_fieldUrl(val){     window.open(val)   }

isValidurl_field2(url: string): boolean {
						    return  /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(url);   } 
						goTourl_field2Url(val){     window.open(val)   }











recaptchaCode = '';  
generaterecaptcha (): void {
  const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const codeLength = 6; // Change to desired length

  let recaptcha= '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * possibleCharacters.length);
    recaptcha += possibleCharacters.charAt(randomIndex);
  }
  this.recaptchaCode = recaptcha;
}

checkrecaptcha(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptchaCode) {
    return { recaptchaMismatch: true };
  }
  return null;
}  

recaptchaMismatch = false;  

checkrecaptchaEdit(): void {
	  if (this.rowSelected.recaptcha  !== this. recaptchaCode) {
	  this. recaptchaMismatch = true;    } else {      this.recaptchaMismatch = false;    }  } 

recaptcha2Code = '';  
generaterecaptcha2 (): void {
  const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const codeLength = 6; // Change to desired length

  let recaptcha2= '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * possibleCharacters.length);
    recaptcha2 += possibleCharacters.charAt(randomIndex);
  }
  this.recaptcha2Code = recaptcha2;
}

checkrecaptcha2(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptcha2Code) {
    return { recaptcha2Mismatch: true };
  }
  return null;
}  

recaptcha2Mismatch = false;  

checkrecaptcha2Edit(): void {
	  if (this.rowSelected.recaptcha2  !== this. recaptcha2Code) {
	  this. recaptcha2Mismatch = true;    } else {      this.recaptcha2Mismatch = false;    }  } 


  // 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
}





















