import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';  // Import BsModalRef
import { trigger, transition, style, animate } from '@angular/animations';
import { MatchService } from '../match.service';
import { AceEditorDirective } from '../ace-editor.directive';
import { SharedService } from '../shared.service';
import { RegexPatternService } from '../services/regexpattern.service';
import { RegexPattern } from '../regex-pattern.model'
import { RegexReplacement } from '../matched-result.model';

@Component({
  selector: 'app-file-browser-modal',
  templateUrl: './file-browser-modal.component.html',
  styleUrls: ['./file-browser-modal.component.css'],
  animations: [
    trigger('fadeAndScale', [
      transition(':enter', [
        style({ opacity: 0, transform: 'scale(0.9)' }),
        animate('300ms  150ms  ease-in', style({ opacity: 1, transform: 'scale(1)' })) // 100ms delay
      ]),
      transition(':leave', [
        animate('300ms  ease-out', style({ opacity: 0, transform: 'scale(0.9)' }))
      ])
    ])
  ]
})
export class FileBrowserModalComponent implements OnInit {
  @ViewChild(AceEditorDirective,  { static: false }) aceEditorDirective!: AceEditorDirective;
  @Input() token: any;
  files: File[] = [];
  searchTerm: string = '';
  fileFilter: string = '*.xml';
  caseInsensitive: boolean = false;
  singleLine: boolean = false;
  multiLine: boolean = false;
  ignoreWhitespace: boolean = false;
  explicitCapture: boolean = false;
  isFileUpload: boolean = false; // Initially set to true to show the File Upload section
  isRegExPatternMinimized: boolean = true; 
  isRegExOptionsMinimized: boolean = true; // State for RegEx Opitons
  isLoading: boolean = false; 
  //transactionId: string;
  directoryPath: string;

  regexPatterns: RegexPattern[] = [];
  selectedPattern: string = '';
  replacementText : string = '';
  previewResults: any[] = [];
  regexReplacement: RegexReplacement;

  constructor(public modalRef: BsModalRef, private regexPatternService: RegexPatternService, private matchService: MatchService, private sharedService: SharedService) { } 

  ngOnInit() {  
     // Subscribe to the observable to get the values
   //  this.sharedService.transactionId$.subscribe((id) => {
    //  this.transactionId = id;
   // });

    this.sharedService.serverPath$.subscribe((path) => {
      this.directoryPath = path;
    });  

    this.loadPatterns();
  }

  loadPatterns(): void {
    this.regexPatternService.getRegexPatterns(this.token).subscribe(
      (data) => {      
        this.regexPatterns = data;
      },
      (error) => {
        console.error('Error fetching regex patterns:', error);
      }
    );
  }

  previewChanges(searchTerm: string, replacementText: string) {
    //debugger;   
    this.isLoading = true;
    
    this.regexReplacement = { 
      directoryPath: this.directoryPath, 
      searchTerm: searchTerm,
      replacementText: replacementText,
      fileType: this.fileFilter,
      caseInsensitive: this.caseInsensitive,
      singleLine: this.singleLine,
      multiLine: this.multiLine,
      ignoreWhitespace: this.ignoreWhitespace,
      explicitCapture: this.explicitCapture 
    }

    this.regexPatternService.previewChanges(this.directoryPath, searchTerm, replacementText, this.fileFilter, this.caseInsensitive, this.singleLine, this.multiLine, this.ignoreWhitespace, this.explicitCapture, this.token)
      .subscribe(results => {     
        this.matchService.setMatches(results);  
        this.matchService.setRegextReplacement(this.regexReplacement)
        this.isLoading = false;      
      },
      (error) => {       
        console.error('Error fetching data:', error);
        this.isLoading = false; // Stop loader on error
      }
    );   
  }

  search(searchTerm: string) {
   // debugger;   
    this.isLoading = true;
    
    this.regexReplacement = { 
      directoryPath: this.directoryPath, 
      searchTerm: searchTerm,
      replacementText: '',
      fileType: this.fileFilter,
      caseInsensitive: this.caseInsensitive,
      singleLine: this.singleLine,
      multiLine: this.multiLine,
      ignoreWhitespace: this.ignoreWhitespace,
      explicitCapture: this.explicitCapture 
    }

    this.regexPatternService.search(this.directoryPath, searchTerm, '', this.fileFilter, this.caseInsensitive, this.singleLine, this.multiLine, this.ignoreWhitespace, this.explicitCapture, this.token)
      .subscribe(results => {     
        this.matchService.setMatches(results);  
       // this.matchService.setRegextReplacement(this.regexReplacement)
        this.isLoading = false;      
      },
      (error) => {       
        console.error('Error fetching data:', error);
        this.isLoading = false; // Stop loader on error
      }
    );   
  }

 
  toggleSection() {
    this.isFileUpload = !this.isFileUpload;
  }

  toggleRegExPattern() {  
    this.isRegExPatternMinimized = !this.isRegExPatternMinimized;         
  }

  toggleRegExOptions() {
    this.isRegExOptionsMinimized = !this.isRegExOptionsMinimized;
  } 

  onFileSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files) {
      // Convert the FileList to an array
      this.files = Array.from(input.files);
     // console.log(this.files); // You can check the uploaded files in the console
    }
  }

  submitSearch() {   
    if (this.files.length > 0) { 
      if(this.aceEditorDirective){
        this.searchTerm = this.aceEditorDirective.getEditorContent();   
     }    
      
     //const regexPatterns = this.searchTerm.split('\n').filter(pattern => pattern.trim() !== '');
     
     this.isLoading = true; 
      this.regexPatternService.uploadFiles(this.files, this.searchTerm, this.fileFilter, this.caseInsensitive, this.singleLine, this.multiLine, this.ignoreWhitespace, this.explicitCapture)
        .subscribe(results => {         
          this.matchService.setMatches(results);
          this.isLoading = false; // Stop loader when data is received        
        },
        (error) => {       
          console.error('Error fetching data:', error);
          this.isLoading = false; // Stop loader on error
        }
      );
    } else {
      alert('Please select files to upload.');
    }
  }
   
 

  readFromServer(directoryPath: string) {    
    if (!directoryPath) {
      // Handle case where directory path is empty or invalid
      return;
    }
    
    if(this.aceEditorDirective){
      this.searchTerm = this.aceEditorDirective.getEditorContent();   
   }        
   //const regexPatterns = this.searchTerm.split('\n').filter(pattern => pattern.trim() !== '');
   
   this.isLoading = true;    
    this.regexPatternService.readFilesFromServer(directoryPath, this.searchTerm, this.fileFilter, this.caseInsensitive, this.singleLine, this.multiLine, this.ignoreWhitespace, this.explicitCapture)
      .subscribe(results => {        
        this.matchService.setMatches(results);  
        this.isLoading = false;    
      },
      (error) => {       
        console.error('Error fetching data:', error);
        this.isLoading = false; // Stop loader on error
      }
    );
  }

  closeModal() {
    this.modalRef.hide();
  }

  isContentEmpty(): boolean {
    return (this.selectedPattern.trim() === '' || this.replacementText.trim() === ''); 
  }

}
