// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  IMPORTS
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Core Angular Imports
//----------------------------------------------------------

import { DatePipe } from "@angular/common";
import { ChangeDetectorRef, Component, ElementRef, OnInit, Renderer2, ViewChild } from "@angular/core";
import { Router } from "@angular/router";
import { Input, Output, ViewContainerRef } from "@angular/core";
import {
  Directive,
  EventEmitter,
  HostListener,
  HostBinding,
} from '@angular/core';
import { Pipe, PipeTransform } from '@angular/core';

//import { EditorChangeContent, EditorChangeSelection } from "ngx-quill";


// Custom Imports
//----------------------------------------------------------------

import { environment } from "../../../../environments/environment";
//import { pagesToggleService } from "../../../@pages/services/toggler.service";
//import { UserCardServiceService } from "../../../../app/_components/user/user-card-service.service";
import { Location } from '@angular/common';
import { ApicallService } from "../../../_services/apiCall/apicall.service";
//import { ChatsvcService } from "../../chatModule/chatsvc.service";
import { NotificationService } from "../notification.service";
import { WebsocketService } from "../../../_services/websocketSVC/websocket.service";
//import { QuillEditorComponent} from "ngx-quill"
//import { Quill} from "quill"

// 3rd Party Libraray Imports
//------------------------------------------------------------------

import { saveAs } from 'file-saver';

//import { touch } from "d3";
import { nullSafeIsEquivalent } from "@angular/compiler/src/output/output_ast";
import { GroupedObservable, Subscription } from "rxjs";
//import { RootLayout } from "../../../@pages/layouts/root/root.component";
//import { I } from "@angular/cdk/keycodes";
//import { subscription } from "rxjs/Subscription";
import { ModalDirective } from "ngx-bootstrap/modal";
import { FormGroupDirective } from "@angular/forms";
import { PopupService } from "src/app/_services/popup/services/popup.service";
import { HttpClient, HttpEvent, HttpEventType } from "@angular/common/http";
import { ChatService } from "../../chatModule/chatsvc.service";
//import { CdkDragDrop, moveItemInArray, transferArrayItem } from "@angular/cdk/drag-drop";
//import { MessageService } from "../../../@pages/components/message/message.service";
declare var pg: any;

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  COMPONENT DECLARATION
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
interface FilePreview {
  file: File;
  url: string;
  filename: number;
  filetype: string;
}

@Component({
  selector: "app-list",
  templateUrl: "./list.component.html",
  styleUrls: ["./list.component.scss"],
})

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  EXECUTION
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 

export class ListComponent implements OnInit {

  editorModules = {
    // https://github.com/KillerCodeMonkey/ngx-quill
    //toolbar: [[{ header: [1, 2, 3, 4, false] }], ['bold', 'italic', 'underline'], ['link', 'image']]
    toolbar: [[{ header: [1, 2, 3, 4, false] }], ['bold', 'italic', 'underline']]
  };
  

// Input Value from Chat Moule and plan component
//-------------------------------------------------------------- 

  @Input() selectedPlan;// not used
  @Input() sendChatModuleValue; // not used
  FormModel: any={}; // form model 

  blured = false// text editor property
  focused = false// text editor property
  private savedRange: Range | null = null;
  private cursorPosition: number = 0;
  // @ViewChild("paymentRef" , { static: true }) paymentRef: ElementRef;

  // @ViewChild("myNameElem" , { static: true }) myNameElem: ElementRef;

  // @ViewChild("editor", { static: true })

  // @ViewChild("addNewFolder", { static: true }) // new folder pop up window  modal directive 
  // public addNewFolder: ModalDirective;

  // @ViewChild("updateFolder", { static: true }) // new folder pop up window  modal directive 
  // public updateFolder: ModalDirective;
  
  // @ViewChild("moveInboxMessageToFolder", { static: true }) // move message to folder pop up window  modal directive 
  // public moveInboxMessageToFolder: ModalDirective;

  // @ViewChild("deleteSldFolder", { static: true }) // Delete folder pop up window  modal directive 
  // public deleteSldFolder: ModalDirective;

  // @ViewChild("deleteSldInbox", { static: true }) // Delete folder pop up window  modal directive 
  // public deleteSldInbox: ModalDirective;

  // @ViewChild("deleteSldFolderMsg", { static: true }) // Delete folder pop up window  modal directive 
  // public deleteSldFolderMsg: ModalDirective;

  @ViewChild("ANF", { static: true }) ANF: FormGroupDirective; // form group for validation
  @ViewChild("AGRP", { static: true }) AGRP: FormGroupDirective; // form group for validation
  @ViewChild("MIMTF", { static: true }) MIMTF: FormGroupDirective; // form group for validation
  @ViewChild('textEditor', { static: false }) textEditor: ElementRef;
   

  
   
 
// ID's
//-------------------------------------------------------------- 
  userID: number; // stores logged user id 
  XBID: number;// stores logged BID 
  BCountryID: number; // not used

  selectedEmail: any = null; // store and display orignal message while click replay 
  subscription; // subsrcption for rxjs
  timeout; // setting timeout method for toggler

// Flags & Switches 
//-------------------------------------------------------------- 
  isEmailSelected = false;// checking is selecting email  or not
  isDraftFolderView: boolean = false; // not used
  isSentSelected = false;// checking is selecting email  or not
  isDraftSelected = false;// checking is selecting email  or not
  isquickviewopen: boolean = false; // not used
  isOpen:boolean=false; // for internal condition checking QV open or closed
  isActiveDelete: boolean = false; // delete icon activation based on checkbox checked
  isCheckInclude: number = 0;// checking Email is include or not while sending message
  isWhatsapp: number = 0;// checking whatsapp is include or not while sending message
  IsLSPlus: number = 1;// checking whatsapp is include or not while sending message
  isDynamicText=0;
  isopendiv: boolean = false; // display message details defult 
  isDisabledinput: boolean = false; // not used
  IsgoToMail: boolean = true;// not used
  isIncludeMail: boolean = false; // checking MNF is include or not while sending message
  isComposeOpen: boolean = false;// open compose window
  isDynamicGroup: boolean = false; // dynamic dg filter activaton binding to html 
  isOrginalMessageActive: boolean = false; // display originl messge, which click reply.
  itemIsRead:boolean=false; // inbox item is read or unread active and deactivate based on value 0/1
  sldsendbutton:boolean=false;// not used
  isMailcomingfromusercard:boolean=false; // click event from user card mail (staff,co-admin,contractor,member)
  isActiveSendbtn: boolean = false; // send button activation if no users not selected means deactivate
  isActiveAdd:boolean=true;
  isActiveDeleteFolder: boolean = false;
  isActiveEdit: boolean = false;
  isActiveCopy:boolean=false
  IsDraft:number=0
  isSaveDraft:boolean=false
  isOpenrightsidebar:boolean=true
  bodyClass: any;// allocates body class css property
  isModalOpen = false;// open model reserve spot
  isModalOpenDelete=false;
  isModalOpenAddFolder=false
  isModalOpenUpdateFolder=false
  isModalOpenDeleteFolder=false
  isModalDeleteFolderMessage=false
  isModalMoveFolderMessage=false;
  isModalOpenDeleteTrash=false;
  isThreadMode:boolean=false // mode thread in inbox
  isTrashOpen:boolean=false
  isLoading=false;
  isMsgFold=true;
  isSendButtonEnabled: boolean = false; // Send Button Status
// Strings 
//------------------------------------------------
  subject = ""; // display subject in compose or reply window sending data to POST API
  message = ""; // display message in compose or reply window once selecting template
  subjecttitle = ""; // display subject in compose or reply window once selecting template
  dearuser:""; // display message in compose or reply window once selecting template
  bodytext:""; // display body text in compose or reply window once selecting template
  bestregards:""; // display best regards in compose or reply window once selecting template
  sign:"";  // display signature in compose or reply window once selecting template
  messageFolderType=""
  messageType = "List"; // his flag for identify clicking inbox or sent button  
  inboxmessageType="List"
  sldIconType = "demo"; // ??
  isType = "Subject"; // identify is to field or what for QV open and close
  firstName = "";  // firstname display binding data to html
  searchedName = ""; // for search name in inbox search box
  apiServer: string = environment.apiUrl; // Server API URL
  notificationURL: string = environment.notificationUrl; // Server API URL
  isOpenDraft:boolean=false
  foldername="";// folder name while adding 
  sldFolderNameForDisplay=""
  sldFolderlist:any;
  foldertype="Selected";
  sldDFID:number // stored selected dFID
  models: any = {};// model Add Folder form
// General 
//------------------------------------------------
  IsReply: number = 0; // binding data to html for sent and inbox onselect method 
  emailgroup: any; // msg list item storing 
  sldtemplate:any; // not used
  selectedJ:any // storing meassge id for html checking 1st mail should active
  userDetailslists:any; // not used
  showmenu:boolean; // for toggle button  hide and show menu
  custommessage:any; // message binding html and send message / reply message
  unreadCount: number=0; // binding html for number of inbox message received
  emailQuotes: number; // binding to html emails details quotes
  emailRemaining: number; // binding to html emails
  msgTemplateId:number =0// identifying template custom or deafault template
  selectedfolderid:any;// selectd folder id
  draftID:any// draft id
  totalInboxCount:number=0// total Inbox count
  totalDraftCount:number=0;// total draft count 
  totalSentCount:number=0;// total sent list count
  totalTrashCount:number=0;// total Trash list count
  hoveredFolder: number | null = null;
  isDownloadModalVisible = false;
  isDownloadComplete = false;
  currentFileName = '';
  currentFileProgress = 0;
// Invoice Generate Details
folderLength:any;
  typeofID:number
  InvoiceId:number;
  ThreadID:number;
  Amount:number;
  bizname=""
  receiverfirstname=""
  receiverlastname=""
  PhoneNumber:number;
  planName=""
  planDuration=""
  receiverCity=""
  receiverCountry=""
  receiverState=""
  receiverDate:any;
  receiverAddress=""
  paymentStatus=""
// End Here Invoice
 sendDetailsintoPayment=[]
  messgaeAccess=""
  groupAccess=""
  templateAccess=""
  messageIndex=""
  messageTempID:any=""
  selectedMessageIDs: Set<number> = new Set(); // Store selected message IDs
// Arrays 
//--------------------------------------------------------------
  subscriptions: Array<Subscription> = []; // subscription array list
  threadList=[]
  sldUsers =[]; // storing all users list from QV
  sldUsersForUserCard:any=[]
  sldUsersmail=[] // not used
  dgFilters = []; // stores dg filter values
  sldGroups = []; // storing all custom and default groups list from QV
  sldDynamicGroups=[];// storing all dynamic groups list from QV
  sldDGFilters = []; // selected dgfilter values 
  receiverIDS = []; // stores receivrer xids for send mail
  userDetails: any = {};// user details stored in local storage
  sentmessageid=[]; // display sender user list in sent 
  sentGroupList=[]// sender group list
  mailUserDetaillist: any={}; // no used
  isSentListTrue=[]
  isDraftListTrue=[]
  isTrashListTrue=[]
  isFolderListTrue=[]
  sldUsersAndGroups: any = { // not used
    
    users: [],
    groups: [],
  };
  sldListDfd=[]// dynamic text field 
  sldDisplayDfd=[]// dynamic text filed
  totalLengthDraftAndFolder=[]// stored Length of draft message
  sldInboxList=[]// selectd inbox list
  unselectUser: any = {}; // unselect from to filed users list
  unselectGroups:any={} // unselect from to filed groups list
  emailList = []; // display inbox and sent msg list
  sentList:any=[]// sent items list
  sldMsgIDS :any= []; // selected message ids for sending mail
  sldMsgIDDrag=[]// selected drag message list
 texteditorModules = {};// not used
  allFolderList=[] // stores all folder list
  sldFolderID:any=[]// selected folder ID
  sldUsersGroupsList=[]// selected group list
  activeSendbtnList=[]// send btn active 
  viewInboxMsgdetails:boolean=false// inbox message menu is active or not
  toviewTotalDraftCount:boolean = false // to view the total draft count
  content=""// contents typed in compose window
  senderdetails=""// sender information
  valueOfDragStart:number// value of drag status
  dyTextAll:any=[]// display all dynamic text 
  trashList=[]
//   Inbox List View with pagination and search
  isSubmitting:boolean=false
  currentPage: number = 1;
  pageStates: number = 1;
  totalPages:number; // Assuming there are 20 pages; adjust as needed.
  itemsPerPage: number = 30;
  searchText: string = '';
  filteredEmailList = []; // Holds the filtered email list after search
  sldFolderMseageDetailsForDelete=[]
  files: File[] = [];// attachment fileswhile compose,replyand forward
  AttachmentPath=[] // display attachments in read meaasges
  selectedFiles: FilePreview[] = [];
  selectedThreadId: number | null = null;
  isAllSelected:boolean = false; //flag for the selectall messages
  folder:any;
  // private selectedUsersSubscription: Subscription;
 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ HEADER +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Constructor
//------------------------------------------------------------------------ 
  constructor(

// A.Declarations 
//------------------------------------------------------

    private location: Location,
    private _service: NotificationService,
   // private toggler: pagesToggleService,
    private staffMail: ChatService,
    private apiCall: ApicallService,
    //private socketSVC: WebsocketService,
    private datePipe: DatePipe,
    private router: Router,
    //private mailService:UserCardServiceService,
    //private _notification: MessageService,
    private notificationService:PopupService,
    private renderer: Renderer2,
    private http: HttpClient,
    private cdr: ChangeDetectorRef
  ) {




//  D.Data coming from service file (commquickview Components) 
// display selected User  in to Field
// -------------------------------------------------------
// ---------------------------------------------------------


// this.selectedUsersSubscription=

 this._service._selectedUsers.subscribe((res) => {
     console.log(this.sldUsers)
      console.log(res);
      this.receiverIDS=[]
      this.sldUsersForUserCard=[]
      this.activeSendbtnList=[]

// stores value from service file into array list
//-------------------------------------------------
     this.sldUsers=res
     this.sldUsersForUserCard=res;
     this.activeSendbtnList.push(res);
      
      
      console.log(this.sldUsersForUserCard)

      if (this.sldUsers.length != 0) {
            for (const item of this.sldUsers) {
              
              console.log(item.XID);
              this.receiverIDS.push(item.XID);
            }

            console.log(this.receiverIDS);
            // this.notificationService.showNotification("Success","Members successfully added");
          }
          console.log(this.receiverIDS);
    });

// ---------------------------------------------------------
// E. Data coming from service file (Template Components) 
// display selected template to compose and replay
// -------------------------------------------------------
// this.resetFields();

this._service._sendtemplate.subscribe((res) => {
  if (!res) return; // Prevent null values

  console.log(res);
  this.subjecttitle = "";  // Reset first
  this.subject = "";

  this.msgTemplateId = res.TemplateID;
  if (res.TemplateID == 1) {
    if (res.subject !== "") {
      this.isDynamicText = 1;
    }

    this.messageIndex = res.Index;
    this.messageTempID = res.MessageTemplateID;
    this.subjecttitle = res.subject;
    this.subject = res.subject;
    this.message = res.Message;
    this.dearuser = res.Dear;
    this.bodytext = res.bodytext;
    this.bestregards = res.bestregards;
    this.sign = res.sign;

    // ✅ Ensure Renderer updates UI correctly
    setTimeout(() => {
      const editor = this.renderer.selectRootElement("#texteditor", true);
      
      // Get existing content before updating
      const existingContent = editor.innerHTML;  
    
      // New template content (should appear first)
      const newContent = `
        <h5 class="contentreply" id="myParagraph"></h5>
        <b>${this.dearuser}</b>
        <p>${this.bodytext}</p>
        <p>${this.bestregards}</p>
        <p>${this.sign}</p>
      `;
    
      // **Prepend** new content before existing content
      this.renderer.setProperty(editor, "innerHTML", newContent + existingContent);
    
      const subt = this.renderer.selectRootElement("#subjecteditor", true);
      this.renderer.setProperty(subt, "innerHTML", this.subjecttitle);
    
      this.cdr.detectChanges();
    }, 0);
  } else {
    if (res.subject !== "") {
      this.isDynamicText = 1;
    }

    this.messageIndex = res.Index;
    this.messageTempID = res.MessageTemplateID;
    this.subjecttitle = res.subject;
    this.bodytext = res.Message;
    this.subject = res.subject;

    console.log(this.bodytext);
  }

  //Force Angular to detect changes immediately
 // this.cdr.markForCheck();
 // this.cdr.detectChanges();
});


// ---------------------------------------------------------
// F.Data coming from service file (commquickview Components) 
// display Group in to Field
// -------------------------------------------------------

this._service._selectedCustomDefaultGroup.subscribe((res) => {
  this.sldGroups=[]
  this.activeSendbtnList=[]
  console.log(res);
  for(let i of res){
    if(i.checked===true){
      this.sldGroups=res;
      this.sldUsersGroupsList=res
      this.activeSendbtnList.push(res);
    }
  }
  
  console.log(this.receiverIDS);

});

// ---------------------------------------------------------
// G.Data coming from service file (commquickview Components) 
// display Group in to Field
// -------------------------------------------------------
this._service._selectedDynamicGroup.subscribe((res) => {
  
  this.activeSendbtnList=[]
  console.log(res);
  this.sldDynamicGroups=res;
 //this.sldUsersGroupsList=res
  //this.sldUsersGroupsList.push(res)
  this.activeSendbtnList.push(res);
  this.sldDynamicGroups.length!=0?this.isDynamicGroup=true:this.isDynamicGroup=false;
  
  console.log(this.receiverIDS);
  
});

// ---------------------------------------------------------
// H.Data coming from service file (UserCArd Components) 
// Open Compose window
// -------------------------------------------------------

//this._service._StaffMail.subscribe((res) => {
  //console.log(res);
  //this.sldUsersForUserCard=res;
//   this.isComposeOpen = true;
//   this.selectedMessageType('Compose');
//   this.isMailcomingfromusercard=true
//   this.getDGFilters();
//  // this.getAllInboxMessages();
//   this.getFolderList()
//   this._service.toggleViewCommunication(this.sldUsersForUserCard, "open");
 

//---------------------------------------------------------

  //});



// call GetInbox message method
//----------------------------------------------------------------------


//-------------------------------------------------------------------------------
// Else Partis Normal Flow 
//-------------------------------------------------------------------------------



// ---------------------------------------------------------
} // constructor End Here
 
 
// Angular LifeCycle 
//----------------------------------------------------

  ngOnInit() {
    const body = document.getElementsByTagName("body")[0];
    body.classList.remove("dashboard");
    body.classList.add("list");
    this.bodyClass = body.classList;
    this._service.toggleViewTemplate("value", "close");
    this.updateSendButtonState();
   //this.updateFilteredData();
  // console.log(this.filteredEmailList); // Check what data is being set
// ------------------------------------------------------------------------ 
// Call Local Storage  

    this.userDetails = JSON.parse(localStorage.getItem("userDetails"));
   // this._service.toggleViewTemplate("value", "close");
    this.userID = this.userDetails.XID;
    this.XBID = this.userDetails.BID;
    
  
// ------------------------------------------------------------------------ 
// ------------------------------------------------------------------------ 
// Call Local Storage  

//this.sldUsersForUserCard = JSON.parse(localStorage.getItem("mailUserinfo"));
let obj=JSON.parse(localStorage.getItem("mailUserinfo"));

const array = [obj];
this.sldUsersForUserCard=array;
console.log(this.sldUsersForUserCard)
// ------------------------------------------------------------------------ 
// compose winow open click user card mail option
// stored in ;local storage and check is value empty or not
// stores XID into receiver IDs array list
// call GetInbox message method
//----------------------------------------------------------------------

if (this.sldUsersForUserCard && this.sldUsersForUserCard[0]!=null) {
  console.log("Hi sldUsersForUserCard Value");
  this.isComposeOpen = true;
  this.selectedMessageType("Compose"); // This should only execute if condition is true
  this.isMailcomingfromusercard = true;

  // Extract XIDs
  this.receiverIDS = this.sldUsersForUserCard.map(user => user.XID);
  this.sldUsers = this.sldUsersForUserCard;

  console.log(this.receiverIDS);
  console.log(this.sldUsers);
} else {
  console.log("Hi Null Value");
  this.inboxmessageType = "List";
  this.selectedMessageType("List");
  this.receiverIDS = [];
  this.sldUsers = [];
  this.isMailcomingfromusercard = false;
  console.log(this.receiverIDS);
}

   
// ------------------------------------------------------------------------ 
// Call toggleViewCommunication Once we load components should close always

    // this._service.toggleViewCommunication("value", "close","null");
    // this.subscription = this._service
    //   .getUnreadCount(this.userID)
    //   .subscribe((res: any) => {
    //     console.log(res);
    //     this.unreadCount = res.Count;
    //   });
  
    // this.timeout = setTimeout(() => {
    //   this.toggler.toggleFooter(false);
    // });

// ------------------------------------------------------------------------ 
// GEt Inbox MEssage Using Socket

// this.socketSVC.getInboxMessage("getinboxmessage-" + this.XBID).subscribe((res: any) => {
//   console.log("hi");
//   console.log(res);
//   if (res.Status === "Success") {
 
//     this.selectedMessageType("List");
//     //this.getFolderList()
//   }
// });




 }    // End angular OnInt() method


  
 

// Angular AfterViewInit method 
// once load onint method after this method willn call  
//----------------------------------------------------- - -------------------------------------

  ngAfterViewInit() {
    if(this.sldUsersForUserCard==null){
    console.log("Hi ngAfterViewInit Value")
    this.inboxmessageType = "List";
    this.getAllDraftMessages();
  
     // Ensure APIs are called in sequence
     this.subscription = this._service .getAllMessages(this.userID,this.XBID).subscribe((res: any) => {
      next: (res) => {
      console.log("Inbox messages loaded:", res);
      // this.getAllDraftMessages();
      this.getAllSentMessages();
      this.getFolderList();
     this.getDGFilters();
     setTimeout(() => {
      this.DynamicGrpList();
    });
      }
    error: (error) => {
      console.error("Error loading inbox messages:", error);
    }
    return;
  });
  

}
setTimeout(() => {
  this.cdr.detectChanges(); // ✅ Ensures Angular detects changes after the view initializes
});
  } // End AfterViewInt()

// Angular ngCheck  
//-------------------------------------------------------------------------------------------
  
  ngDoCheck() {
   
    if (this.subject !== "" && this.receiverIDS.length > 0) {
      this.isActiveSendbtn = true;
    } else {
      this.isActiveSendbtn = false;
    }
   
   }

 
// Angular DEstroy Method 
//--------------------------------------------------------------------------------------------

  ngOnDestroy() {
    // for(const sub of this.subscription){
    //   sub.unsubscribe();
    // }
    this.sldUsersForUserCard=null
    localStorage.removeItem("mailUserinfo");
    this.isMailcomingfromusercard=false
    this.sldUsersForUserCard=null
    this.receiverIDS=[]

    this.sldUsers = [];
    this.sldGroups = [];
    this.sldDGFilters=[]
    this.sldDynamicGroups=[]
    this.isComposeOpen = false;
    this.sldUsersmail=[]
    this.subscription=[]
    this.sldUsersGroupsList=[]
     this.activeSendbtnList=[]
    const body = document.getElementsByTagName("body")[0];
    body.classList.remove("list");
    // if (this.selectedUsersSubscription) {
    //   this.selectedUsersSubscription.unsubscribe();
    // }
  }

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  METHODS
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------
/**
   * @method function
   * @name onFileChange
   * @description  Check if the file already exists in the selectedFiles array
   * @param {event}
   */
 
 onFileChange(event: any) {
  const selectedFiles = event.target.files;
  console.log(selectedFiles.length);
  console.log(this.selectedFiles.length);

  for (let i = 0; i < selectedFiles.length; i++) {
    const file = selectedFiles[i];

    // Check if file size is less than 200KB
    if (file.size <= 200 * 1024) {
      
      const isDuplicate = this.selectedFiles.some(
        (existingFile) => existingFile.filename === file.name && existingFile.file.size === file.size
      );

      if (!isDuplicate) {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          this.selectedFiles.push({
            file,
            url: e.target.result,
            filename: file.name,
            filetype: file.type,
          });

          console.log("File added:", this.selectedFiles);
        };
        reader.readAsDataURL(file);
      } else {
        this.notificationService.showNotification("Error", `${file.name} is already added.`);
      }
    } else {
      this.notificationService.showNotification("Error", `${file.name} exceeds the 200KB size limit.`);
    }
  }

  // Reset the file input to allow re-adding the same file
  event.target.value = null;

  console.log("Final Selected Files:", this.selectedFiles);
}

/**
   * @method function
   * @name removeFile
   * @description  // Remove the file from the array
   * @param {index}
   */
 
removeFile(index: number) {
  console.log("Removing file at index:", index);
  this.selectedFiles.splice(index, 1); 
  console.log("Updated Selected Files:", this.selectedFiles);
}
/**
   * @method function
   * @name removeAttachedFile
   * @description  // Remove the AttachmentPath from the array
   * @param {index}
   */
removeAttachedFile(index:number){
  console.log(index)
  console.log(this.AttachmentPath)
  this.AttachmentPath.splice(index,1)
  // this.getPaginatedData().forEach((ele)=>{if(ele.AttachmentPath[index]==this.AttachmentPath[index]){ele.AttachmentPath.splice(index,1)}})
}
/**
   * @method function
   * @name clearMessageManually
   * @description clears the messages from text
  
   */
clearMessageManually() {
  const currentText = this.textEditor.nativeElement.innerHTML.trim();
  if (!currentText) {
    this.bodytext = '';
    this.dearuser = '';
    this.bestregards = '';
    this.sign = '';
  }
}

/**
   * @method convertTo24Hour
   * @name view convert 12hrs to 24hrs
   * @description this method is used to convert the res time 12hr format to 24hr format
   
*/

convertTo24Hour(time12h: string): string {
  if (!time12h) return ''; // Handle empty values safely

  // Ensure time format matches "hh:mm AM/PM"
  const match = time12h.match(/^(\d{1,2}):(\d{2})\s?(AM|PM)$/i);
  if (!match) return time12h; // Return original if format is incorrect

  let hours = parseInt(match[1], 10);
  const minutes = match[2];
  const modifier = match[3].toUpperCase();

  if (modifier === 'PM' && hours !== 12) {
    hours += 12;
  } else if (modifier === 'AM' && hours === 12) {
    hours = 0;
  }

  // Ensure two-digit hour format
  return `${hours.toString().padStart(2, '0')}:${minutes}`;
}



/**
   * @method toggleViewThreadMode
   * @name view mode thread mode and normal mode
   * @description Mode inbox
   
*/

toggleViewThreadMode(value){
  console.log(value)
  if(this.messageType === 'List'){
  
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllInboxMessages()
    this.getAllInboxThread()
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
    this.isAllSelected=false
  }
  else if(value=="normal"){
    this.isThreadMode=false
    this.getPaginatedDataForList()
    this.getAllInboxMessages()
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
  }
}
else if(this.messageType === 'Sent'){
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllSentMessages()
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
  }
  else if(value=="normal"){
    this.isThreadMode=false
    this.getAllSentMessages()
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
  }
}

else if(this.messageType === 'Draft'){
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllDraftMessages()
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
    this.isAllSelected=false
  }
  else if(value=="normal"){
    this.isThreadMode=false
   this.getAllDraftMessages()
   this.sldMsgIDS = [];
   this.sldFolderMseageDetailsForDelete = [];
   this.isAllSelected=false
  }
}
else if(this.messageType === 'Trash'){
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllTrashMessages()
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
  }
  else if(value=="normal"){
    this.isThreadMode=false
   this.getAllTrashMessages()
   this.sldMsgIDS = [];
   this.sldFolderMseageDetailsForDelete = [];
  }
}

else if(this.messageType === 'FolderView'){
  if(value=="thread"){
    this.isThreadMode=true
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
  //  this.getSelectedFolderMessages(this.allFolderList[0])
  this.getSelectedFolderMessages(this.sentList)
  }
  else if(value=="normal"){
    this.isThreadMode=false
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
   // this.sentList=[]
  // this.getSelectedFolderMessages(this.allFolderList[0])
  }
}
  console.log(this.isThreadMode)
}






/**
   * @method 
   * @name GoPaymentPage()
   * @description navigate by url
   
*/


GoPaymentPage(){

  //this.router.navigateByUrl("notification/payments");
  this.router.navigate(["/notification/payments"])
}
/**
   * @method dragStart
   * @name Drag Methods implementation
   * @description msg drag and drop to folders 
   
*/

dragStart(event,val) {
  console.log("Drag Start")
 
 console.log(val)
 this.valueOfDragStart=0
 this.sldMsgIDDrag=val.MessageID;
 
}

/**
   * @method dragover
   * @name Drop Methods implementation
   * @description msg drag and drop to folders 
   * Drop to folder one mesage no duplicate upload to folder 
   */
dragover(event,val) {
 
  console.log("drag Over ++++++++++++++++++++++")

  if(this.valueOfDragStart===0){
    this.dropOver(event,val)
     this.valueOfDragStart=1;
     console.log(this.valueOfDragStart)
  }

}
/**
   * @method dropOver
   * @name Drop Methods implementation
   * @description msg drag and drop to folders 
   * once we done drop message into folder call API to update respective message into folder
   * POST API - updatemessagefolders
   * Folder ID, Message ID,XID and BID
   */

dropOver(event,val){
 console.log(val)
 console.log("Drop------------------------------------------------")
 this.sldFolderlist=[]
 this.sldFolderlist=val.FolderID

// API Call---------------------------------------------------

    const url = this.notificationURL + "notifications/updatemessagefolders";
    
// POST USer Details------------------------------------------------
  
     const UserDeatils = {
      
        FolderID:this.sldFolderlist,
        XBID: this.XBID, 
        XID: this.userID,
       // MessageIDs: this.sldMsgIDDrag.toString()   
       MessageIDs:this.sldMsgIDS.toString() 
     };
   console.log(UserDeatils);
  
// API CAll
// POST------------------------------------------------------
  
     this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
      console.log(res);

// API Response
// check th success message and call GetFolder API -----------------
// showing notification

     if (res.Status === "Success") {
      
    this.getFolderList()
    this.sldFolderlist=[]
    // this._notification.remove()
    // this._notification.create("success", "Messages are Added Sucessfully", {
    //         Position: "top-right",
    //         Style: "flip bar",
    //         Duration: 3000,
    //       });
    this.notificationService.showNotification("Success","Messages are added successfully.");
    this.valueOfDragStart=1;
  
  }

// ELSE Condition
// show notification error message , already Exist -----------------
        else{
         this.sldFolderlist=[]
    //       this._notification.remove()
    //      this._notification.create("danger", "Message Already Exist", {
    //         Position: "top-right",
    //         Style: "flip bar",
    //         Duration: 3000,
    // });
    this.notificationService.showNotification("Error","Message already exist");
//-------------------------------------------------------------------
// Set value as 0 and call refresh URL

         this.valueOfDragStart=0;
         let currentUrl = this.router.url;
         this.router.routeReuseStrategy.shouldReuseRoute = () => false;
         this.router.onSameUrlNavigation = "reload";
         this.router.navigate([currentUrl]); 
        }
         
     });


}

//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------

/**
   * @method Method
   * @name showDeleteFolderMsgWindow 
   * @description Folder Message Deleted show
*/

showDeleteFolderMsgWindow(){
//  this.deleteSldFolderMsg.show()
}

/**
   * @method Method
   * @name hideDeleteFolderMsgWindow
   * @description Folder Message Deleted hide
*/
hideDeleteFolderMsgWindow(){
 // this.deleteSldFolderMsg.hide()
}

/**
   * @method Method
   * @name deleteFolderMessageList
   * @description Folder Message Deleted
   
   */

deleteFolderMessageList(){

// store message Id's
//------------------------------------
let deletefolderid=this.sldMsgIDS.toString()

// Call API-------------------------------------

const url =this.notificationURL + "notifications/deletefoldermessagebymessageid/" + this.XBID +"/" + this.userID + "/" + this.selectedfolderid + "/" + this.foldertype;

// POST API ----------------------------------------------------------

this.apiCall.makePostApiCall(url,  this.sldFolderMseageDetailsForDelete).then((res: any) => {
      console.log(res);

// Check The API Response ----------------------------------------------------------
// Refresh Current URL
// Show Notification Message
//Hide Modal window
// change flags value to FolderView

if (res.Status === "Success") {
      
    let curfold=this.sentList
     this.sldFolderMseageDetailsForDelete=[]
       this.getFolderList()
      //  this.refreshCard("Folder")
       //this.getSelectedFolderMessages(null)
       this.sldMsgIDS=[]
       console.log(this.selectedMessageIDs);
      this.closeDeleteFolderMessageWindow()
      this.notificationService.showNotification("Success","Folder messgae deleted sucessfully.");
      this.getSelectedFolderMessages(curfold)
     
      console.log(curfold);
      
      // this.deleteSldFolderMsg.hide()
        this.isActiveDelete = false;
        this.messageType = ""
        this.messageType = "FolderView"
        this.selectedEmail = null;
    
      
      }
    });
   
     
}

 /**
   * @method Method
   * @name logChange
   * @description change Event
   */

  logChange($event){

    console.log(this.selectedEmail)
    console.log($event)

   }



  

// -------------------------------------------------------------------------------


/**
   * @method Method
   * @name triggerUpdateFolder
   * @description Update Folder Submit Method
*/


triggerUpdateFolder(form){
  console.log(form) 
  if (form.valid) {
    console.log('Form submitted:', this.foldername);
    this.updateNEWFolder();
    form.reset(); // Reset only after successful form submission
    this.closeAddFolderWindow();
  } else {
    console.log('Form is invalid');
    this.markFormControlsTouched(form); // Mark controls as touched to show validation errors
  }
  
  if (!form.valid) {
    this.markFormControlsTouched(form);
  }
  
  }

  markFormControlsTouched(form) {
    Object.keys(form.controls).forEach(key => {
      const control = form.controls[key];
      control.markAsTouched();
      control.updateValueAndValidity(); // Ensure the UI updates correctly
    });
  }

 /**
   * @method Method
   * @name triggerMoveInbox
   * @description  Folder selection Form message move Validation one click create button
   
   */
triggerMoveInbox(){
   
  this.MIMTF.onSubmit(undefined);
}

  /**
   * @method Method
   * @name showAddFolderWindow
   * @description open add folder pop up window 
   */

showAddFolderWindow(){
  this.foldername=""
 this.isModalOpenAddFolder=true
}
/**
   * @method function
   * @name closeAddFolderWindow
   * @description close add folder pop up window 
   */
closeAddFolderWindow(){
 // this.foldername =""
  this.isModalOpenAddFolder=false
  this.isModalOpenUpdateFolder=false
 }

 /**
   * @method function
   * @name showUpdateFolderWindow
   * @description show  update folder pop up window 
   */
showUpdateFolderWindow(value){
  console.log(value)
  console.log(this.sentList.FolderName);
  console.log(this.foldername); 
  this.foldername=value.FolderNam
  this.sldFolderID=value.FolderID;
 this.isModalOpenUpdateFolder=true
}
/**
   * @method function
   * @name openDeleteFolderMessageWindow()
   * @description open delete folder message window
   */
openDeleteFolderMessageWindow(){
  this.isModalDeleteFolderMessage=true
  this.selectFolderType('Only');
}

/**
   * @method function
   * @name closeDeleteFolderMessageWindow()
   * @description close delete folder msg window
   */
closeDeleteFolderMessageWindow(){
  this.isModalDeleteFolderMessage=false
}
/**
   * @method function
   * @name selectFirstFolder()
   * @description cselects folder messages
   */
selectFirstFolder(foldID) {
  if (this.allFolderList && this.allFolderList.length > 0) {
    const firstFolder = this.allFolderList[0];
    if(foldID==this.allFolderList[0].FolderID){
    this.getSelectedFolderMessages(this.allFolderList[1]);
    }
    else{
      this.getSelectedFolderMessages(firstFolder);
    }
    console.log(firstFolder)
  } else {
    console.error("No folders available to select.");
  }
}
/**
  * @method Method
  * @name showCopyInboxMessageWindow
  * @description open Move inbox message to folder pop up window 
*/
showCopyInboxMessageWindow(){
console.log(this.sldMsgIDS);
console.log(this.selectedMessageIDs);

this.isModalMoveFolderMessage=true
     
}

/**
   * @method Method
   * @name closeCopyInboxMessageWindow
   * @description moveinbox folder pop up window close
   * Refresh Card Inbox
*/
closeCopyInboxMessageWindow(){
  this.isModalMoveFolderMessage=false
  this.sldFolderlist=[]
}
/**
  * @method Method
  * @name showDeleteFolderWindow
  * @description delete  folder pop up window 
*/

showDeleteFolderWindow(){ 
  this.isModalOpenDeleteFolder=true
//  this.deleteSldFolder.show()
}
/**
  * @method function
  * @name showDeleteTrashWindow
  * @description  shows the trash window value
*/
showDeleteTrashWindow(value){
  
  if(value=="All"){
  this.sldInboxList.forEach(item => {
    item.displayTime  = this.formatDateOrTime(item.Date);
    if(item.displayTime!='Invalid Date'){
    this.sldMsgIDS.push(item.MessageID)
    }
  });
}
  this.isModalOpenDeleteTrash=true
}



/**
   * @method Method
   * @name closeDeleteTrashWindow
   * @description trash folder
*/

closeDeleteTrashWindow(){
  this.isModalOpenDeleteTrash=false
  this.sldMsgIDS=[]
}

/**
   * @method Method
   * @name updateNEWFolder
   * @d POST API updatefoldername
   * Update Folder name with name , folder ID and XID
*/

  updateNEWFolder(){
    let fold=this.foldername
    if (this.foldername .length > 25) {
      this.notificationService.showNotification("Error", "Folder name cannot exceed 25 characters.");
      return; // Exit the function without proceeding further
    }
   const url = this.notificationURL + "notifications/updatefoldername";
     const UserDeatils = [{
        FolderName: this.foldername, 
        FolderID:this.sldFolderID,
        XID: this.userID
     }];
//-----------------------------------------------------------------------
// Call POST API

     this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
      console.log(res);

// Check the response value
//----------------------------------------------------------------
      if (res.status === "Success") {
        this.foldername=fold
        this.getFolderList()
       this.closeAddFolderWindow()
        this.notificationService.showNotification("Success","Folder updated successfully.");
        this.isActiveEdit=false;
        this.isActiveAdd=true;
        this.isActiveDeleteFolder=false
        this.sldFolderID=null
      }

// ELSe condition show notification error message and reset form
//----------------------------------------------------------------      
      else{
  
    
      this.notificationService.showNotification("Error","Somethings Went Wrong");
        this.isActiveEdit=false;
        this.isActiveAdd=true;
        this.isActiveDeleteFolder=false
        this.sldFolderID=null
      }

     });
     
    }

/**
   * @method Method
   * @name triggerAddFolder
   * @description Add Folder Form Validation one click create button
*/

triggerAddFolder(form){
  console.log(this.allFolderList)
console.log(form)
 this.isSubmitting = true;
  if (form.valid) {
    console.log('Form submitted:', this.models);
    this.saveNewFolder()
    this.isSubmitting = false;
  } else {
    console.log('Form is invalid');
  }

    // Prevent further actions if already submitting
    if (this.isSubmitting) return;
  
    // Set submitting flag to true
    this.isSubmitting = true;
  
    // Perform form submission logic here (e.g., API call)
    // Example: Simulate an API call with setTimeout
    setTimeout(() => {
      // Form submission logic here
      console.log('Form submitted:', this.foldername);
  
      // Reset form and submission status after completion
     
      this.isSubmitting = false;
     // this.closeAddFolderWindow();
    }, 1000); // Simulating API response time
  

}
/**
   * @method Method
   * @name saveNewFolder
   * @description Save Folder USing POST API savemessagefolder
*/
saveNewFolder(){
     
// API Call--------------------------------------------------------------
 // Validate group name length
 if (this.foldername .length > 25) {
  this.notificationService.showNotification("Error", "Folder name cannot exceed 25 characters.");
  return; // Exit the function without proceeding further
}
  const url = this.notificationURL + "notifications/savemessagefolder";
    
// POST USer Details-------------------------------------------------------------
  const UserDeatils = {
    FolderID:null,
    XBID: this.XBID, 
    XID: this.userID,
    FolderName: this.foldername    
    
  };
     
// API CAll
// POST------------------------------------------------------
 
  this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
  console.log(res);

// Sucess Conditions
// Reset Form and Call Method GetfolderList ()------------------------

  if (res.Status === "Success") {
       // this.addNewFolder.hide()
       // this.ANF.resetForm()
      //  this.selectFirstFolder()
       
       this.closeAddFolderWindow();
       this.selectedfolderid=this.sentList.FolderID
       this.getFolderList()
       if(this.sentList.length==0){this.getSelectedFolderMessages(this.allFolderList[0])}
       else{this.getSelectedFolderMessages(this.sentList)}
       console.log(this.sentList);
       console.log(this.allFolderList);
       this.foldername =""
        this.notificationService.showNotification("Success","Folder added successfully.");
  }
// Else
// Reset Form and show error message------------------------------------
  else{
      
      this.notificationService.showNotification("Error","Somethings Went Wrong");

  }

    });
}

/**
   * @method Method
   * @name getFolderList
   * @description Get Folder List API  getmessagefolders
*/
getFolderList(){
 console.log(this.foldername);
 this.isLoading=true
  const url =this.notificationURL +"notifications/getmessagefolders/" +this.XBID +"/" +this.userID;

// API Call
//-----------------------------------------------------------------

  this.apiCall.makeGetApiCall(url).then((res: any) => {
    console.log(res)
    
    this.isLoading=false
//success stores folder List into array
//-----------------------------------------------------------------
   if(res.Status==="Success"){
     this.allFolderList=res.FolderDetails;
     console.log(this.foldername);
   }
  

// Failure Empty Array List
//-----------------------------------------------------------------
   else if(res.status===417 || res.statusText=="Expectation Failed"){
    this.allFolderList=[];
   
   // this.messageType=""
  }

  console.log(this.allFolderList)
  //this.AGRP.resetForm()
  //this.ANF.resetForm()
  this.isAllSelected==false


  });
  


}  

/**
   * @method Method
   * @name triggerAddFolder
   * @description Add Folder Form Validation one click create button
*/

triggerAddMessageToFolder(form){
  console.log(form)
   
    if (form.valid) {
      console.log('Form submitted:', this.models);
      this.addMessageToSelecetdFolder()
  
    } else {
      console.log('Form is invalid');
    }
  
  
  }




/**
   * @method Method
   * @name addMessageToSelecetdFolder
   * @description Update Folder 
*/

addMessageToSelecetdFolder(){
  console.log(this.sldFolderlist)

// API Call ------------------------------------------------------------------
 const url = this.notificationURL + "notifications/updatemessagefolders";
// POST USer Details ----------------------------------------------------------

 let source=""
 if(this.messageType=="List"){
  source="Inbox"
  }
   else if(this.messageType=="Sent"){
     source="Sent"
    }
 else if (this.messageType=="Draft"){
  source="Draft"
 }
 else if (this.messageType=="FolderView"){
  source="Folder"
 }
 else{
  source="Trash"
 }
console.log(this.sldFolderlist);
this.sldMsgIDS=[]
console.log(this.sldMsgIDS);

  this.sldFolderMseageDetailsForDelete.forEach((ele)=>{
    this.sldMsgIDS.push(ele.MessageID)
  })

console.log(this.sldMsgIDS);

  const UserDeatils = {
    FolderID:this.sldFolderlist,
    XBID: this.XBID, 
    XID: this.userID,
    MessageIDs: this.sldMsgIDS.toString(),   
    Source:source
  };

// API CAll
// POST------------------------------------------------------

   this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
    console.log(res);

// Response Success
// Show Message in notification and reset form and call Get Folder List ---------

   if (res.Status === "Success") {
        //this.moveInboxMessageToFolder.hide()
        this.getFolderList()
        this.sldFolderlist=[]
        this.closeCopyInboxMessageWindow()
        if(this.messageType=="List"){
          this.refreshCard("List")
        }
        else if(this.messageType=="Sent"){
          this.refreshCard("Sent")
        }
        else if(this.messageType=="FolderView"){
          this.refreshCard("Folder")
        }
        else if(this.messageType=="Draft"){
          this.refreshCard("Draft")
        }
        else if(this.messageType=="Trash"){
          this.refreshCard("Trash")
        }
        this.sldFolderMseageDetailsForDelete=[]
      
        
        this.notificationService.showNotification("Success","Messages successfully moved to "+this.folder+" folder");
      }

// Else
// Show Error Message and hide Modal-----------------------------------------------
      else{
        this.closeCopyInboxMessageWindow()
        if(this.messageType=="List"){
          this.refreshCard("List")
        }
        else if(this.messageType=="Sent"){
          this.refreshCard("Sent")
        }
        else if(this.messageType=="FolderView"){
          this.refreshCard("Folder")
        }
        else if(this.messageType=="Draft"){
          this.refreshCard("Draft")
        }
        else if(this.messageType=="Trash"){
          this.refreshCard("Trash")
        }
        this.sldFolderlist=[]
        this.sldFolderMseageDetailsForDelete=[]
        this.notificationService.showNotification("Error","Message already exist");
      }

    
      
   });

}
/** 
   * @method function
   * @name selectedFolder
   * @description show the folder name 
*/
selectedFolder(value){
  console.log(value);
  this.folder=value.FolderName

  
}
/** 
   * @method Method
   * @name onSelectFolderList
   * @description Select folder Message via Check Box
   * and Stored selected folder message into array
   * if unchecked remove form array using findIndex Method
*/

onSelectFolderList(value,event){
  console.log(value)
  const checked = event.target.checked;
  this.foldername=value.FolderName
  this.isActiveEdit=false;
  this.isActiveAdd=true;
  this.isActiveDeleteFolder=false
//-------------------------------------------------------------
// Checekd Event

  if (checked) {
    this.sldFolderID=value.FolderID;
    this.isActiveEdit=true;
    this.isActiveAdd=false;
    this.isActiveDeleteFolder=true
  } 
//-------------------------------------------------------------------
// Unchecked Event

  else {
  const index = this.sldFolderID.findIndex((obj) => obj === value.FolderID);
  this.sldFolderID.splice(index, 1);
  this.isActiveEdit=false;
  this.isActiveAdd=true;
  this.isActiveDeleteFolder=false
  }

console.log(this.sldFolderID)

}



/** 
   * @method Method
   * @name selectFolderType
   * @description shows the selected folder type
*/

selectFolderType(value){
console.log(value)
if(value==="Only"){
  this.foldertype="Selected"
}
else{
  this.foldertype="All"
}
}

/** 
   * @method Method
   * @name DeleteAllTrash
   * @description delete Trash From trash all
   * POST API deletemessagefolder
   * Folder Id,XID and BID
*/
DeleteAllTrash(){
  let source=""
  if(this.isModalOpenDeleteTrash===true) {
     source="All"
  }
  else{
    source="Selected"
  }
  
   const url =this.notificationURL + "notifications/deletemessagesfromtrash/" + this.XBID + "/" + this.userID + "/" + source;

//------------------------------------------------------
// POST API

 this.apiCall.makePostApiCall(url, this.sldMsgIDS).then((res: any) => {
   console.log(res);
   console.log(this.sldMsgIDS);
  // return false;
//------------------------------------------------------
// Response is Success
// call Sent API
   if (res.Status === "Success") {
     this.sldMsgIDS=[]
     this.notificationService.showNotification("Success","Trash successfully emptied.");
     this.messageType = ""
     this.messageType = "Trash"
     this.selectedEmail = null;
     this.refreshCard("Trash")
     this.getAllTrashMessages()
     this.closeDeleteTrashWindow()
     this.isTrashOpen=false
     
   }
 });

}

/** 
   * @method Method
   * @name deleteSelectedFolder
   * @description delete Message From selected folder  
   * POST API deletemessagefolder
   * Folder Id,XID and BID
*/
 deleteSelectedFolder(){


  const url = this.notificationURL + "notifications/deletemessagefolder/" + this.foldertype;
    
// POST USer Details
   const UserDeatils = {
      FolderID:this.sldFolderID,
      XBID: this.XBID, 
      XID: this.userID
   };

   console.log(UserDeatils);

// API CAll
// POST------------------------------------------------------
this.isLoading=true
this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
    console.log(res);
   

this.isLoading=false
// Success Message
// Call Method and show success msg----------------------

    if(res.Status==="Success"){
      // this.deleteSldFolder.hide()
     
      // this.sldFolderID=[]
      // this._notification.create("success", "Folder Deleted Sucessfully", {
      //   Position: "top-right",
      //   Style: "flip bar",
      //   Duration: 3000,
      // });
      
      this.notificationService.showNotification("Success","Folder successfully deleted.");
      this.getFolderList()
      console.log(this.allFolderList);
      
      if(this.allFolderList.length>1){
        this.selectFirstFolder(this.sldFolderID);
      }
     
      if(this.allFolderList.length===1){
        this.selectedMessageType("List")
      }
      this.closewindowModel()
      this.isActiveEdit=false;
      this.isActiveAdd=true;
      this.isActiveDeleteFolder=false

    }

// Else Part
// Hide Modal and show error message ----------------------------- 

   else{
    // this.deleteSldFolder.hide()
    // this._notification.create("danger", "Somethings Went Wrong", {
    //   Position: "top-right",
    //   Style: "flip bar",
    //   Duration: 3000,
    // });
    this.notificationService.showNotification("Error","Somethings Went Wrong");

    this.isActiveEdit=false;
    this.isActiveAdd=true;
    this.isActiveDeleteFolder=false
     }
  });

}

/**
   * @method Method
   * @name getAllInboxMessages
   * @description   this is used to take a specified line of messaage 
   
*/
 getAllInboxThread(){
  this.threadList=[]
  this.subscription = this._service .getAllThread(this.userID,this.ThreadID).subscribe((res: any) => {
    console.log(res);
   // if(res.threadList.length>0){
      this.threadList=res.threadMessages;
   // }
   console.log(this.threadList)
   
   if(this.isThreadMode==true){
   // this.onSelectInbox(res[0])
  }
   
// for the dynamic data that is stored in an array

this.threadList.forEach((item) => {
  const lines = item.Message.split('\n').map((line) => line.trim()); // Split by line and trim whitespace
  item.ShortMessage = lines.find((line) =>
    line.startsWith('Your')
  ) || ''; // Find the specific line or fallback to empty
  console.log(item.ShortMessage);
  
});
  });
 }
/**
   * @method Method
   * @name  toggleThread
   * @description it show the selected thread id. 
   * @param {Index,item}
*/
//  toggleThread(item,index: number): void {
//   console.log(item)
//   this.selectedThreadId = this.selectedThreadId === index ? null : index;
// }

toggleThread(item: any, i: number) {
  if (this.selectedThreadId === i) {
    // If the same message is clicked, close it
    this.selectedThreadId = null;
  } else {
    // Otherwise, open the clicked message
    this.selectedThreadId = i;
  }
}


/**
   * @method Method
   * @name getAllInboxMessages
   * @description All Inbox Message
   * @GET API getAllMessages
*/
getAllInboxMessages() {

  this.isLoading=true
    this.emailList = [];
    this.sldInboxList=[];
    this.selectedEmail=[]
    this.filteredEmailList=[]
this.isComposeOpen=false;
this.isAllSelected=false
//-----------------------------------------------------------
// API Call

  this.subscription = this._service .getAllMessages(this.userID,this.XBID).subscribe((res: any) => {
 
    
      console.log(res);
      this.emailList=res;
       this.sldInboxList=res
       this.isLoading=false
      this.sldInboxList.forEach((item )=> {
       
        item.displayTime  = this. formatDateOrTime(item.Date);
        item.Time=this. convertTo24Hour(item.Time);
        }
       
      );
      //this.sldInboxList=res
     
     
// Check the response length 
//---------------------------------------------------------------------------------    
        res.length > 0 ?((this.emailList = res),
        (this.getGymRole()),(this.totalPages = Math.ceil(this.emailList.length / this.itemsPerPage)),
        (this.totalInboxCount=res[res.length-1].TotalUnreadMessageCount),(this.viewInboxMsgdetails=true), (this.toviewTotalDraftCount=true)) : ((this.emailList = []));

        if(this.isThreadMode==true){
          this.onSelectInbox(res[0])
        }
        this.updateFilteredData()
        this.calculateTotalPages();

  });  


 
  
}


/**
   * @method Method
   * @name hexToRgba
   * @description conver into rgb to hexa decimal value color plan

   
*/
hexToRgba(hex: string, opacity: number): string {
  if (!/^#([A-Fa-f0-9]{6})$/.test(hex)) {
    //console.error('Invalid hex color:', hex);
    return `rgba(227, 177, 0, ${opacity})`; // Default to black with given opacity
  }

  const cleanHex = hex.replace('#', '');
  const r = parseInt(cleanHex.substring(0, 2), 16);
  const g = parseInt(cleanHex.substring(2, 4), 16);
  const b = parseInt(cleanHex.substring(4, 6), 16);

  return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}
/**
   * ~ deselectInboxMessageAll
     Selected message unselect
   * # Method 
*/
deselectInboxMessageAll(){
  if(this.messageType=="List"){
    this.refreshCard("List")
  }
  else if(this.messageType=="Sent"){
    this.refreshCard("Sent")
  }
  else if(this.messageType=="FolderView"){
    this.refreshCard("Folder")
  }
  else if(this.messageType=="Draft"){
    this.refreshCard("Draft")
  }
  else if(this.messageType=="Trash"){
    this.refreshCard("Trash")
  }
  
   console.log("DeselectAll")
  // this.emailList.forEach(item => {
  //   item.checked = false;
  // });
 
  this.sldMsgIDS=[]
  this.sldFolderMseageDetailsForDelete=[];
}
/**
   * @method Method
   * @name formatDateOrTime() {
   * @description Date format Inbox sent draft
*/
formatDateOrTime(dateString: string | Date): string {
  const messageDate = new Date(dateString);
  const today = new Date();

  if (messageDate.toDateString() === today.toDateString()) {
    return messageDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  } else {
    return messageDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  }
}

DynamicGrpList(): void {
  const addRecipientInput = document.getElementById('add-recipient-input');
  const dgFilterGroups = document.querySelectorAll('.dg-filter-group');

  if (addRecipientInput && dgFilterGroups.length > 0) {
    if (addRecipientInput.parentElement) {
      addRecipientInput.parentElement.appendChild(addRecipientInput);
    }
  }
}



/**
   * @method Method
   * @name updateFilteredData() {
   * @description Seach Inbox sent draft
*/
updateFilteredData() {
  this.filteredEmailList = this.sldInboxList.filter(item => { 
    const fullName = `${item.SenderFirstName} ${item.SenderLastName}`.toLowerCase();
    let groupMatch = [];
    let receiverMatch = [];
    
    if (this.messageType === 'Sent' || this.messageType === 'Draft') {    
      if (item.GroupIDs) {
        groupMatch = item.GroupIDs.filter(group => {
          const fname = `${group.RecieverFirstName} ${group.RecieverLastName}`;
          return group.RecieverGroupName.toLowerCase().includes(this.searchText.toLowerCase()) ||
            fullName.includes(this.searchText.toLowerCase());
        });
      }
      if (item.RecieverXIDs) {
        receiverMatch = item.RecieverXIDs.filter(receiver => {
          const fname = `${receiver.RecieverFirstName} ${receiver.RecieverLastName}`;
          return receiver.RecieverFirstName.toLowerCase().includes(this.searchText.toLowerCase()) || 
                 receiver.RecieverLastName.toLowerCase().includes(this.searchText.toLowerCase()) ||
                 fname.includes(this.searchText.toLowerCase());
        });
      }
    }

    return (
      (item.SenderFirstName && item.SenderFirstName.toLowerCase().includes(this.searchText.toLowerCase())) ||
      (item.SenderLastName && item.SenderLastName.toLowerCase().includes(this.searchText.toLowerCase())) ||
      (item.Subject && item.Subject.toLowerCase().includes(this.searchText.toLowerCase())) ||
      (item.Message && item.Message.toLowerCase().includes(this.searchText.toLowerCase())) ||
      (item.Time && item.Time.toLowerCase().includes(this.searchText.toLowerCase())) ||
      (fullName.includes(this.searchText.toLowerCase())) ||
      (receiverMatch.length > 0) || 
      (groupMatch.length > 0)
    );
  });

  // ✅ If search is cleared, reset selection to the first message
  if (this.searchText.trim() === '') {
    this.filteredEmailList = [...this.sldInboxList]; // Restore original list
  }

  // ✅ Ensure the first message is selected
  if (this.filteredEmailList.length > 0) {
    this.selectedEmail = this.filteredEmailList[0];
    this.InvoiceId=this.filteredEmailList[0].MessageID
    this.sldFolderlist=this.filteredEmailList[0].MessageID
    this.draftID=this.filteredEmailList[0].MessageID
  }
}

/**
   * @method function
   * @name getPaginatedData()
   * @description it shows total data of page 
   */
getPaginatedData() {
  const startIndex = (this.currentPage - 1) * this.itemsPerPage;
  return this.filteredEmailList.slice(startIndex, startIndex + this.itemsPerPage); 
  
}
/**
   * @method function
   * @name getPaginatedDataForList()
   * @description it shows total data of page list
   */
getPaginatedDataForList() {  
  const startIndex = (this.currentPage - 1) * this.itemsPerPage;
  return this.filteredEmailList.slice(startIndex, startIndex + this.itemsPerPage);
}
/**
   * @method function
   * @name onPageChange()
   * @description it shows changes in current page and state
   */
onPageChange(page: number) {
  console.log("Before Page Change:", this.isAllSelected, "Page:", page);

  if (typeof page === 'number' && page > 0 && page <= this.totalPages) {
    this.currentPage = page;
    this.pageStates = page;
    this.isActiveDeleteFolder = false;
    
    // Reset all checkboxes when changing pages
    //this.getPaginatedData().forEach((item) => (item.checked = false));

    console.log("After Page Change:", this.currentPage);
  } else {
    console.warn("Invalid page number:", page);
  }
  this.updateSelectAllState();
}

 /**
   * @method function
   * @name goToPreviousPage()
   * @description it shows the previous page
   */

goToPreviousPage() {
  console.log(this.isAllSelected)
  if (this.currentPage > 1) {
    this.currentPage--;
    // this.onPageChange(this.currentPage);
    if(this.isAllSelected=true){
   // this.isAllSelected=true
    }
    else{
     //this.isAllSelected=false
    }
  }
  this.updateSelectAllState();
}
 /**
   * @method function
   * @name goToNextPage()
   * @description it shows the next page
   */
goToNextPage() {
  console.log(this.filteredEmailList);
  
  console.log(this.isAllSelected)
  if (this.currentPage < this.totalPages) {
    this.currentPage++;
    // this.onPageChange(this.currentPage);
    //this.isAllSelected=false
   // this.getPaginatedData().forEach((item) => (item.checked = false)); 
  }
  this.updateSelectAllState();
}
/**
   * @method function
   * @name updateSelectAllState()
   * @description it shows the updated state
   */
updateSelectAllState() {
  let u=this.getPaginatedData();
  if( this.isThreadMode==true){
  if(this.messageType=='List'){this.onSelectInbox(u[0])}
  else{this.onSelect("null",u[0])}
  this.selectedEmail=u[0]
  }
  const hasCommon = u.some(itemA => this.sldFolderMseageDetailsForDelete.some(itemB => itemA.MessageID === itemB.MessageID));
  console.log(hasCommon);
  if(hasCommon==false){
    this.isMsgFold=false
   
  }else{this.isMsgFold=true}
  console.log(this.sldFolderMseageDetailsForDelete);
  this.isAllSelected = this.getPaginatedDataForList().every(item => item.checked);

  
  console.log(this.isAllSelected);
}
/**
   * @method function
   * @name getDisplayedPages
   * @description it shows total and large pages 
   */
getDisplayedPages(): (number | string)[] {
  
  const pages: (number | string)[] = [];
  const maxDisplayedPages = 5; // Show at most 5 page numbers

if (this.totalPages <= 1) return pages;
if(this.messageType=="List"){
  if (this.totalPages <= maxDisplayedPages) {
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(i);
    }
  } else {
    if (this.currentPage <= 3) {
      pages.push(1, 2, 3, '...', this.totalPages);
    } else if (this.currentPage >= this.totalPages - 2) {
      pages.push(1, '...', this.totalPages - 2, this.totalPages - 1, this.totalPages);
    } else {
      pages.push(1, '...', this.currentPage - 1, this.currentPage, this.currentPage + 1, '...', this.totalPages);
    }
  }

  return pages;
}
if (this.totalPages <= 1) return pages;
if(this.messageType=="Sent"){
  if (this.totalPages <= maxDisplayedPages) {
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(i);
    }
  } else {
    if (this.currentPage <= 3) {
      pages.push(1, 2, 3, '...', this.totalPages);
    } else if (this.currentPage >= this.totalPages - 2) {
      pages.push(1, '...', this.totalPages - 2, this.totalPages - 1, this.totalPages);
    } else {
      pages.push(1, '...', this.currentPage - 1, this.currentPage, this.currentPage + 1, '...', this.totalPages);
    }
  }

  return pages;
}
if (this.totalPages <= 1) return pages;
if(this.messageType=="Draft"){
  if (this.totalPages <= maxDisplayedPages) {
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(i);
    }
  } else {
    if (this.currentPage <= 3) {
      pages.push(1, 2, 3, '...', this.totalPages);
    } else if (this.currentPage >= this.totalPages - 2) {
      pages.push(1, '...', this.totalPages - 2, this.totalPages - 1, this.totalPages);
    } else {
      pages.push(1, '...', this.currentPage - 1, this.currentPage, this.currentPage + 1, '...', this.totalPages);
    }
  }

  return pages;
}
if (this.totalPages <= 1) return pages;
if(this.messageType=="Trash"){
  if (this.totalPages <= maxDisplayedPages) {
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(i);
    }
  } else {
    if (this.currentPage <= 3) {
      pages.push(1, 2, 3, '...', this.totalPages);
    } else if (this.currentPage >= this.totalPages - 2) {
      pages.push(1, '...', this.totalPages - 2, this.totalPages - 1, this.totalPages);
    } else {
      pages.push(1, '...', this.currentPage - 1, this.currentPage, this.currentPage + 1, '...', this.totalPages);
    }
  }

  return pages;
}
if (this.totalPages <= 1) return pages;
if(this.messageType=="FolderView"){
  if (this.totalPages <= maxDisplayedPages) {
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(i);
    }
  } else {
    if (this.currentPage <= 3) {
      pages.push(1, 2, 3, '...', this.totalPages);
    } else if (this.currentPage >= this.totalPages - 2) {
      pages.push(1, '...', this.totalPages - 2, this.totalPages - 1, this.totalPages);
    } else {
      pages.push(1, '...', this.currentPage - 1, this.currentPage, this.currentPage + 1, '...', this.totalPages);
    }
  }

  return pages;
}
}
/**
   * @method function
   * @name calculateTotalPages()
   * @description it shows current and total  pages 
   */
calculateTotalPages(): void {
  this.totalPages = Math.ceil(this.filteredEmailList.length / this.itemsPerPage);
}
// nextPage() {
//   if ((this.currentPage * this.itemsPerPage) < this.filteredEmailList.length) {
//     this.currentPage++;
//   }
// }

// previousPage() {
//   if (this.currentPage > 1) {
//     this.currentPage--;
//   }
// }
/**
   * @method function
   * @name onSearchChange()
   * @description it shows current and total  pages 
   */
onSearchChange() {
  this.currentPage = 1;
  this.updateFilteredData();
  this.calculateTotalPages();
}

 /**
   * @method Method
   * @name getSelectedFolderMessages
   * @description Get All MEssages for Slected Folder using GET API getallmessagesinfolder
   */

 getSelectedFolderMessages(value){
  this.currentPage=1
  this.searchText=''
  this.folderLength=value.FolderLength
  console.log(this.folderLength);
  this.isActiveDelete=false
  this.sldMsgIDS=[]
  this.messageType=""
  this.inboxmessageType=""
  this.foldername=""
  this.messageType ="FolderView"   
  this.selectedfolderid=value.FolderID
  this.sldFolderID=value.FolderID;
   this.foldername=value.FolderName
 this.sldFolderNameForDisplay=value.FolderName
 this.isAllSelected=false
   this.backToFolderView()
   this.getDGFilters()
  console.log(value)
  this.sldFolderMseageDetailsForDelete=[]
  this.emailList = [];
  this.sentList =[]
  this.sentList = value;
    this.sldInboxList=[]
    this.sentmessageid=[]
    this.activeSendbtnList=[]  
    this.filteredEmailList=[]
    console.log(this.sentList);
    this.totalLengthDraftAndFolder=[]
    console.log(this.selectedfolderid);
    
//--------------------------------------------------------------------------------
// API Called Here
this.isLoading=true
// console.log(this.selectedfolderid);
// if(this.selectedfolderid==this.allFolderList[0].FolderID){
//   this.selectedfolderid=this.allFolderList[1].FolderID 
// }
console.log(this.allFolderList);

const url = this.notificationURL + "notifications/getallmessagesinfolder/" + this.XBID + "/" + this.userID + "/" + this.selectedfolderid;
this.apiCall.makeGetApiCall(url).then((res: any) => {
  this.isLoading=false
  
console.log(res)
// Check The Response Here
//------------------------------------------------------------------------------------------
 if(res.length!==0){
  this.emailList=res;
  this.totalLengthDraftAndFolder=res
  this.sldInboxList=res
  this.sldInboxList.forEach(item => {
    item.displayTime  = this.formatDateOrTime(item.Date);
  });
  this.isAllSelected=false
  this.updateFilteredData()
  this.calculateTotalPages();
  if(this.isThreadMode==true){
    //this.onSelect("null",res[0])
   // if(this.isThreadMode==true){
      this.onSelect("null",res[0])
   // }
  }
  this.totalPages = Math.ceil(this.emailList.length / this.itemsPerPage)
}
// Eror Message 
// -------------------------------------------------------------------------
 if(res.statusText=="Expectation Failed"){
  this.emailList = [];
  this.totalLengthDraftAndFolder=[]
  this.isComposeOpen=false
 }

});

}
//-------------------------------------------------------------------------------------------------
/**
   * @method Method
   * @name getAllSentMessages
   * @description All Sent Message
   * @GET API getAllSentMessages
*/
 getAllSentMessages() {
  let st=performance.now();
  
    this.sentList = [];
    this.sldInboxList=[]
    this.isSentListTrue=[]
    this.sentmessageid=[]
    this.activeSendbtnList=[]
    this.filteredEmailList=[]
    this.isAllSelected=false
// Call GET API getAllSentMessages
//---------------------------------------------------------------------------------  

    this.subscription = this._service.getAllSentMessages(this.userID).subscribe((res: any) => {
      let et=performance.now();
      console.log(st);
      console.log(et);
      console.log(et-st);
      
    console.log(res);
    this.totalSentCount=res[res.length-1].TotalSentMessage
    this.sentList = res;
    this.emailList =res
// Check the Response Length
//---------------------------------------------------------------------------------  
 if(res.length>=1){
  console.log(this.sentList);
  console.log(this.emailList); 
        this.sentList = res;
       this.isSentListTrue=res
       this.sldInboxList=res
       this.sldInboxList.forEach(item => {
        item.Time = this.convertTo24Hour(item.Time);
         item.displayTime  = this.formatDateOrTime(item.Date);
       });
       console.log('the converted 24hr format:',this.sldInboxList);
       this.updateFilteredData()
       this.calculateTotalPages();
       this.totalPages = Math.ceil(this.emailList.length / this.itemsPerPage)
       if(this.isThreadMode==true){
        this.onSelect("null",res[0])
      }

 }

     
  });
 


}

 /**
   * @method Method
   * @name getAllDraftMessages
   * @description Get All Draft Message Here
   * GET API getAllDraft with XID and BID
   */

 getAllDraftMessages(){
  let std=performance.now();
  this.totalLengthDraftAndFolder=[]
  this.emailList = [];
  this.selectedEmail=[]
  this.sentList = [];
  this.sldInboxList=[]
  this.sentmessageid=[]
  this.activeSendbtnList=[]
  this.filteredEmailList=[]
  this.isAllSelected=false
  //-----------------------------------------------------------
  // API Call

  this.subscription = this._service
    .getAllDraft(this.userID,this.XBID)
    .subscribe((res: any) => {
      let etd=performance.now();
      console.log(etd-std);
      
      console.log(res);
// Check Result Length is greater than 0 , allocates response into array
//-------------------------------------------------------------------
       this.sldInboxList=res
       this.emailList=res;
      //  this.totalDraftCount=res[res.length-1].TotalDraftMessage
      //  console.log(this.totalDraftCount);
       this.sldInboxList.forEach(item => {
        item.Time = this.convertTo24Hour(item.Time);
         item.displayTime  = this.formatDateOrTime(item.Date);
       });
      res.length > 0? ((this.emailList = res),(this.totalDraftCount=res[res.length-1].TotalDraftMessage),(this.totalPages = Math.ceil(this.emailList.length / this.itemsPerPage)),
      (this.totalLengthDraftAndFolder=res),(this.toviewTotalDraftCount=false)) : ((this.emailList = []));
      this.updateFilteredData()
      this.calculateTotalPages();
// Check Result Length is 1,make it empty
//-------------------------------------------------------------------        
    if(res.length==1){
      this.emailList = []
      this.totalLengthDraftAndFolder=[]
    }
    if(this.isThreadMode==true){
      this.onSelect("null",res[0])
      
    }
console.log(this.totalLengthDraftAndFolder)
console.log(this.isComposeOpen)
console.log(this.messageType)
console.log(this.isThreadMode)
// Check Result Length is greater than 1 
// Call OnSelect Method for select default 
// check Message Type and User Card Value
//-------------------------------------------------------------------  
    
      
    });

 
}

/**
   * @method Method
   * @name getAllTrashMessages
   * @description Get All Draft Message Here
   * GET API getAllDraft with XID and BID
   */

getAllTrashMessages(){
  this.trashList=[]
  this.emailList = [];
  this.selectedEmail=[]
  this.sentList = [];
  this.sldInboxList=[]
  this.sentmessageid=[]
  this.activeSendbtnList=[]
  this.filteredEmailList=[]
  this.sldMsgIDS=[]
  this.isAllSelected=false
  //-----------------------------------------------------------
  // API Call

  this.subscription = this._service
    .getAllTrash(this.userID,this.XBID)
    .subscribe((res: any) => {
      
      
      console.log(res);

// Check Result Length is greater than 0 , allocates response into array
//-------------------------------------------------------------------
       this.sldInboxList=res
       this.sldInboxList.forEach(item => {
        item.Time = this.convertTo24Hour(item.Time);
         item.displayTime  = this.formatDateOrTime(item.Date);
        //  if(item.displayTime!='Invalid Date'){
        //  this.sldMsgIDS.push(item.MessageID)
        //  }
       });
      res.length > 0? ((this.emailList = res),(this.totalPages = Math.ceil(this.emailList.length / this.itemsPerPage)),
      (this.trashList=res)) : ((this.emailList = []));
      this.updateFilteredData()
      this.calculateTotalPages();
// Check Result Length is 1,make it empty
//-------------------------------------------------------------------        
    if(res.length==0 || res.statusText=="Expectation Failed"){
      this.emailList = []
      this.trashList=[]
    }

    if(this.isThreadMode==true){
      this.onSelect("null",res[0])
    }
// Check Result Length is greater than 1 
// Call OnSelect Method for select default 
// check Message Type and User Card Value
//-------------------------------------------------------------------  
    
      
    });

 
}

/**
   * @method function
   * @name backToInboxList()
   * @description  it shows last page inbox list
   
   */
backToInboxList(){
  this.itemIsRead=false;
  this.inboxmessageType="List"
  this.isComposeOpen=false;
  this.selectedEmail=[]
  this.sldUsersForUserCard=[]
  this.sldUsers=[]
  localStorage.removeItem("mailUserinfo");
 //this.isThreadMode=false
 // this.selectedMessageType("List")
}
/**
   * @method function
   * @name backToSentList()
   * @description  it move back to send list
   
   */
backToSentList(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'Sent'
  console.log(this.isSentListTrue)
  this.sldUsers=[]
  localStorage.removeItem("mailUserinfo");
  this.isComposeOpen=false;
}
/**
   * @method function
   * @name backToDraftList()
   * @description  it move back to Drafts list
   
   */
backToDraftList(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'Draft'
  this.sldUsers=[]
  localStorage.removeItem("mailUserinfo");
  this.isComposeOpen=false;
}
/**
   * @method function
   * @name backToTrashList()
   * @description  it move back to Trash list
   
   */
backToTrashList(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'Trash'
  //this.isThreadMode=false
  this.isDraftFolderView=false;
  this.isTrashOpen=false;
}
/**
   * @method function
   * @name backToFolderView()
   * @description  it move back to Trash list
   
   */
backToFolderView(){
  this.isDraftFolderView=false
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'FolderView'
 // this.isThreadMode=false
  this.isTrashOpen=false;
  this.isComposeOpen=false;
}
//------------------------------------------------------------------------------------ 
/**
   * @method Method
   * @name onSelectInbox
   * @description Select Inbox Message
   * Inbox list messge selection and open View Window
*/

onSelectInbox(value){
  let sentmessageids=[]
  this.sldFolderMseageDetailsForDelete=[]
  // Check if the selected message is already open
   this.toggleThread(value,null)
  this.draftID=value.MessageID;
  this.sldFolderMseageDetailsForDelete.push(value.MessageID)
  if(this.isThreadMode==true){
    console.log(value)
    this.selectedEmail = value;
    this.AttachmentPath=value.AttachmentPath
    this.InvoiceId=value.MessageID
    this.ThreadID=value.ThreadID
    this.updateReadMessage();
    this.updateViewCount();
    this.sldMsgIDS=[]
    this.subject = this.selectedEmail.Subject;
    this.message = this.selectedEmail.Message;
    this.sldMsgIDS.push(value.MessageID);

    // if(value.ThreadID==null){

    //   this.getAllInboxThread()
 
    //  }

  
    if(value.ThreadID!=null){

      this.getAllInboxThread()
 
     }


    if(value.Type==2){
      this.InvoiceId=value.MessageID // invoice Id only
      this.Amount=value.Amount
      this.bizname=value.BizName
      this.receiverfirstname=value.ReceiverFirstName
      this.receiverlastname=value.ReceiverLastName
      this.PhoneNumber=value.PhoneNumber
      this.planName=value.PlanName
      this.planDuration=value.PlanDuration
      this.receiverAddress=value.Address
      this.receiverDate=value.Date
      this.receiverCity=value.City
      this.receiverCountry=value.Country
      this.receiverState=value.State
      this.paymentStatus=value.PaymentStatus
      this.sendDetailsintoPayment=value
      localStorage.setItem("userPlanDetails", JSON.stringify(this.sendDetailsintoPayment));
      console.log(this.sendDetailsintoPayment)
      }
      for(const i of value.RecieverXIDs){
        if(i!==null){
        console.log(i.RecieverFirstName)
        sentmessageids.push(i.RecieverFirstName+" "+i.RecieverLastName)
        }
              
      }
      this.sentmessageid=sentmessageids;
  }
  else{
    this.itemIsRead=true;
    this.selectedJ="" 
   // let sentmessageids=[]
    this.selectedJ=value.MessageID
    console.log(this.messageType);
    console.log(this.isComposeOpen);
    this.isSentSelected=false
    for(const i of value.RecieverXIDs){
      if(i!==null){
      console.log(i.RecieverFirstName)
      sentmessageids.push(i.RecieverFirstName+" "+i.RecieverLastName)
      }
            
    }
    this.sentmessageid=sentmessageids;
  // assign message and subject into variables
  //------------------------------------------------------------------  
    this.selectedEmail = value;
    this.AttachmentPath=value.AttachmentPath
    this.isEmailSelected = true;
    this.sldMsgIDS=[]
    this.subject = this.selectedEmail.Subject;
    this.message = this.selectedEmail.Message;
    this.sldMsgIDS.push(value.MessageID);
    this.isopendiv = true;
    console.log(value);
    this.typeofID=value.Type
    if(value.Type==2){
    this.InvoiceId=value.MessageID // invoice Id only
    this.Amount=value.Amount
    this.bizname=value.BizName
    this.receiverfirstname=value.ReceiverFirstName
    this.receiverlastname=value.ReceiverLastName
    this.PhoneNumber=value.PhoneNumber
    this.planName=value.PlanName
    this.planDuration=value.PlanDuration
    this.receiverAddress=value.Address
    this.receiverDate=value.Date
    this.receiverCity=value.City
    this.receiverCountry=value.Country
    this.receiverState=value.State
    this.paymentStatus=value.PaymentStatus
    this.sendDetailsintoPayment=value
    localStorage.setItem("userPlanDetails", JSON.stringify(this.sendDetailsintoPayment));
    console.log(this.sendDetailsintoPayment)
    }
    console.log(value.MessageID);
  
  // Call Update View Count and ReadMessage API
  //---------------------------------------------------------------  
      this.messageType="List"
      this.updateReadMessage();
      this.updateViewCount();
  
  // Call GetAllInbox API
  //---------------------------------------------------------------     
      this.subscription = this._service.getAllMessages(this.userID,this.XBID).subscribe((res: any) => {
        console.log(res);
        res.length > 0 ? (this.sldInboxList = res) : (this.emailList = []);
  
      });
     
  }
 
}


/**
   * @method Method
   * @name onSelect
   * @description Select Inbox or sent message and Draft for view    
  * @Call updateReadMessage() and updateViewCount()
*/
onSelect(item,value) {
  this.itemIsRead=false;
 this.inboxmessageType="";
  this.sentGroupList=[]
  let sentmessageids=[]
  this.receiverIDS=[]
  this.selectedEmail = value;
  this.selectedJ=value.MessageID
  this.isDynamicGroup=false
  this.isopendiv = true;
  console.log(value);
  console.log(this.sldUsers);
  this.sldFolderMseageDetailsForDelete=[]
  this.sldFolderMseageDetailsForDelete.push(value.MessageID)
  //this.isOpenDraft=false
// ---------------------------------------------------------------------------------------------------  
// ---------------------------------------------------------------------------------------------------        
// If Sent means this Block it wil call   
this.draftID=value.MessageID;

if(this.messageType === "Sent"){
  if(this.isThreadMode==true){
    this.sldFolderlist=value.MessageID
    this.selectedEmail = value;
    this.AttachmentPath=value.AttachmentPath
    this.sldMsgIDS=[]
 
  this.sldMsgIDS.push(value.MessageID);
  for(let i of value.RecieverXIDs){
    if(i!==null){
    console.log(i.RecieverFirstName)
    sentmessageids.push(i.RecieverFirstName+" "+i.RecieverLastName)
    }       
  }
      
  if(value.GroupIDs !=null){
    for(const i of value.GroupIDs){
      if(i!==null){
      console.log(i.RecieverGroupName)
      this.sentGroupList.push(i.RecieverGroupName)
      }
         
    }
  }
  this.sentmessageid=sentmessageids;
  }
  else{
  console.log( this.msgTemplateId)
  this.selectedEmail = []
  this.selectedEmail = value;
  this.AttachmentPath=value.AttachmentPath
  this.isSentSelected=true
  this.inboxmessageType=""
  this.sentmessageid=[]
  this.sldMsgIDS=[]
  this.sldFolderlist=value.MessageID
  this.sldMsgIDS.push(value.MessageID);
  for(const i of value.RecieverXIDs){
    if(i!==null){
    console.log(i.RecieverFirstName)
    sentmessageids.push(i.RecieverFirstName+" "+i.RecieverLastName)
    }
          
  }
  //this.sentmessageid=sentmessageids;
  if(value.GroupIDs !=null){
    for(const i of value.GroupIDs){
      if(i!==null){
      console.log(i.RecieverGroupName)
      this.sentGroupList.push(i.RecieverGroupName)
      }
         
    }
  }
  this.sentmessageid=sentmessageids;
}
console.log(this.sentmessageid)
}
      
 
       
  this.selectedEmail = value;
  //this.isEmailSelected = true;
  this.subject = this.selectedEmail.Subject;
  this.message = this.selectedEmail.Message.replace(/\n|\r/g, "");

// ---------------------------------------------------------------------------------------------------  
// ---------------------------------------------------------------------------------------------------        
// If Draft means this Block it wil call   
      
if(this.messageType === "Draft"){
  console.log(this.getPaginatedData());
    this.isSentSelected=false
    this.sldUsers=[]
    this.sldGroups=[]
    this.sldDynamicGroups=[]
    this.inboxmessageType=""
    this.isOpenDraft=true
    this.subjecttitle=value.Subject
    this.content=value.Message
    this.isSaveDraft=true;
    this.sldMsgIDS.push(value.MessageID);
    console.log(this.AttachmentPath)
    console.log(value)
    this.IsLSPlus=value.IsLSPlus
    this.isWhatsapp=value.IncludeMail

    this.isCheckInclude=value.IsWhatsapp
   if(this.isThreadMode==false){
   this.isComposeOpen=true;
   this.draftID=value.MessageID;
   }
   else{
    this.isComposeOpen=false;
    this.isOpenDraft=false
    this.draftID=value.MessageID;
   }
   this.AttachmentPath=value.AttachmentPath;
// ---------------------------------------------------------------------------------------------------        
// Check receiver XID's not null     

  if(value.RecieverXIDs[0]!=null){
        for (let j of value.RecieverXIDs){
          const ids={
              XID:j.RecieverXID,
              checked: true,
              firstName: j.RecieverFirstName,
              image: j.RecieverProfilePicture,
              lastName: j.RecieverLastName
          }
          this.sldUsers.push(ids)
          this.receiverIDS.push(j.RecieverXID)
      
         }

  }

// ---------------------------------------------------------------------------------------------------        
// Check rGroup Id Length notnull and its greater than 0 

  if(value.GroupIDs.length >= 1 && value.GroupIDs!=null){
    for (let j of value.GroupIDs){
      if(j.GroupType=="Dynamic"){
        const ids={
          groupID:j.RecieverGroupID,
          groupName:j.RecieverGroupName,
          groupType:j.GroupType
          }
            this.isDynamicGroup=true
            this.sldDynamicGroups.push(ids)
            }
          else{
            const ids={
              groupID:j.RecieverGroupID,
              groupName:j.RecieverGroupName,
              groupType:j.GroupType  
            }
  
            this.sldGroups.push(ids)
            }
            
          }
  }
 console.log(this.sldGroups);
      
}


if(this.messageType === "Trash"){
 
  this.inboxmessageType=""
  
  this.subjecttitle=value.Subject
  this.content=value.Message
  this.isSaveDraft=true;
  this.draftID=value.TrashMessageID;
 console.log(value)

 if(this.isThreadMode==false){
 this.isTrashOpen=true;
 
 }
 else{
  this.isTrashOpen=false;
 }
// ---------------------------------------------------------------------------------------------------        
// Check receiver XID's not null     

this.sldFolderlist=value.MessageID
this.selectedEmail = value;
this.AttachmentPath=value.AttachmentPath
this.sldMsgIDS=[]

this.sldMsgIDS.push(value.MessageID);
for(const i of value.RecieverXIDs){
if(i!==null){
console.log(i.RecieverFirstName)
sentmessageids.push(i.RecieverFirstName+" "+i.RecieverLastName)
}
      
}
  
if(value.GroupIDs !=null){
for(const i of value.GroupIDs){
  if(i!==null){
  console.log(i.RecieverGroupName)
  this.sentGroupList.push(i.RecieverGroupName)
  }
     
}
}
this.sentmessageid=sentmessageids;

if(value.Source=="Draft" && this.isThreadMode==false){
  this.sldUsers=[]
  this.receiverIDS=[]
  this.sldGroups=[]
  this.sldDynamicGroups=[]
  this.isDraftFolderView=true;
 // this.isComposeOpen=true;
if(value.RecieverXIDs[0]!=null){

for (let j of value.RecieverXIDs){
  const ids={
      XID:j.RecieverXID,
      checked: true,
      firstName: j.RecieverFirstName,
      image: j.RecieverProfilePicture,
      lastName: j.RecieverLastName
  }
  this.sldUsers.push(ids)
  this.receiverIDS.push(j.RecieverXID)

 }

}

// ---------------------------------------------------------------------------------------------------        
// Check rGroup Id Length notnull and its greater than 0 

if(value.GroupIDs.length >= 1 && value.GroupIDs!=null){
for (let j of value.GroupIDs){
if(j.GroupType=="Dynamic"){
const ids={
  groupID:j.RecieverGroupID,
  groupName:j.RecieverGroupName
  }
    this.isDynamicGroup=true
    this.sldDynamicGroups.push(ids)
    }

  else{

    const ids={
      groupID:j.RecieverGroupID,
      groupName:j.RecieverGroupName
       
    }

    this.sldGroups.push(ids)
    }
    
  }
}
}
    
}


if(this.messageType === "FolderView"){
 
  this.inboxmessageType=""
  this.isComposeOpen=false;
  this.subjecttitle=value.Subject
  this.content=value.Message
  this.isSaveDraft=true;
  this.draftID=value.MessageID;
 console.log(value)
 this.IsLSPlus=value.IsLSPlus
 this.isWhatsapp=value.IncludeMail

 this.isCheckInclude=value.IsWhatsapp
 if(this.isThreadMode==false){
 this.isTrashOpen=true;

 }
 else{
  this.isTrashOpen=false;
 }

 if (this.draftID===value.MessageID) {
  this.isOpenDraft = true; // Set isOpenDraft to visible
}
// ---------------------------------------------------------------------------------------------------        
// Check receiver XID's not null     

this.sldFolderlist=value.MessageID
this.selectedEmail = value;
this.AttachmentPath=value.AttachmentPath
this.sldMsgIDS=[]

this.sldMsgIDS.push(value.MessageID);
for(const i of value.RecieverXIDs){
if(i!==null){
console.log(i.RecieverFirstName)
sentmessageids.push(i.RecieverFirstName+" "+i.RecieverLastName)
}
      
}
  
if(value.GroupIDs !=null){
for(const i of value.GroupIDs){
  if(i!==null){
  console.log(i.RecieverGroupName)
  this.sentGroupList.push(i.RecieverGroupName)
  }
     
}
}
this.isDraftFolderView=false;
this.sentmessageid=sentmessageids;

  if(value.Source=="Draft" && this.isThreadMode==false){
    this.sldUsers=[]
    this.receiverIDS=[]
    this.sldGroups=[]
    this.sldDynamicGroups=[]
    this.isDraftFolderView=true;
    this.isComposeOpen=true;
  if(value.RecieverXIDs[0]!=null){

  for (let j of value.RecieverXIDs){
    const ids={
        XID:j.RecieverXID,
        checked: true,
        firstName: j.RecieverFirstName,
        image: j.RecieverProfilePicture,
        lastName: j.RecieverLastName
    }
    this.sldUsers.push(ids)
    this.receiverIDS.push(j.RecieverXID)

   }

}

// ---------------------------------------------------------------------------------------------------        
// Check rGroup Id Length notnull and its greater than 0 

if(value.GroupIDs.length >= 1 && value.GroupIDs!=null){
for (let j of value.GroupIDs){
if(j.GroupType=="Dynamic"){
  const ids={
    groupID:j.RecieverGroupID,
    groupName:j.RecieverGroupName
    }
      this.isDynamicGroup=true
      this.sldDynamicGroups.push(ids)
      }

    else{

      const ids={
        groupID:j.RecieverGroupID,
        groupName:j.RecieverGroupName
         
      }

      this.sldGroups.push(ids)
      }
      
    }
}
}


}
// ---------------------------------------------------------------------------------------------------  
// ---------------------------------------------------------------------------------------------------        
// If Inbox means this Block it wil call

  if(this.messageType === "List"){
        this.messageType="List"
        this.updateReadMessage();
        this.updateViewCount();
        this.inboxmessageType="List"
        this.subscription = this._service.getAllMessages(this.userID,this.XBID).subscribe((res: any) => {
        console.log(res);  
        res.length > 0 ? (this.sldInboxList = res) : (this.emailList = []);
        });
    } 

       
}
// --------------------------------------------------------------------------------------------------- 
// ---------------------------------------------------------------------------------------------------  

/**
   * @method Method
   * @name   getUnreadMessages() 
   * @description GET API Call   
*/

getUnreadMessages() {
    this._service.getUnreadCount(this.userID).subscribe((res: any) => {
      console.log(res);
      this.unreadCount = res.Count;
    });
}

// --------------------------------------------------------------------------------------------------

/**
   * @method Method
   * @name   refreshCard() 
   * @description API Call List / Sent   
*/
refreshCard(value) {
    //value = this.messageType;
    console.log(value)
    
this.sldMsgIDS = [];
this.sldFolderMseageDetailsForDelete = [];
this.isActiveDelete = false;
this.isActiveCopy = false;
this.isAllSelected=false;
console.log(value)
// If Value Is List refresh Inbox
//--------------------------------------------------------    
    value === "List"
      ? ((this.messageType = "List"),
        this.getAllInboxMessages(),this.getPaginatedDataForList(),
        (this.sldMsgIDS = []),
        (this.isComposeOpen = false),
        (this.selectedEmail = null),
        (this.sldDGFilters = []))
// If Value Is Sent refresh Sent Items
//--------------------------------------------------------  

      : value === "Sent"
      ? ((this.messageType = "Sent"),this.getPaginatedData(),
        this.getAllSentMessages(),
        (this.sldMsgIDS = []),
        (this.isComposeOpen = false),
        (this.selectedEmail = null),
        (this.isOrginalMessageActive = true),
        (this.sldDGFilters = []))

      : value === "Draft"
      ? ((this.getPaginatedData()),(this.sldMsgIDS = []),(this.messageType="Draft"),(this.getAllDraftMessages()),(this.isComposeOpen = false),(this.sldDGFilters = []),
      (this.selectedEmail = null))

      : value === "Trash"
      ? ((this.getPaginatedData()),(this.sldMsgIDS = []),(this.messageType="Trash"),(this.getAllTrashMessages()),(this.isComposeOpen = false),(this.sldDGFilters = []))

      : value === "Folder"
      ? ((this.getPaginatedData()),(this.sldMsgIDS = []),(this.messageType="Folder"),(this.getFolderList()),(this.isComposeOpen = false),(this.sldDGFilters = []),
      (console.log(this.allFolderList[0].FolderID)),
      setTimeout(() => {
        if (this.allFolderList && this.allFolderList.length > 0) {
         let foldeId={
          FolderID :this.allFolderList[0].FolderID
            
          }
          
          console.log(foldeId); // Log the FolderID
          this.getSelectedFolderMessages(this.sentList); // Call getSelectedFolderMessages after 2 seconds
        } else {
          console.error('No folders available');
        }
      }, 0))// 1 seconds delay
    

//-----------------------------------------------------------------
// Else null 
      : null;
}


// ------------------------------------------------------------------------------------------------
/**
   * @method Method
   * @name   reply() 
   * @description click reply or forward btn it will open compose window 
*/

reply(value) {
  this.msgTemplateId=0
  this.messageType = value;
  this.inboxmessageType="List"
  this.sldUsers=[]
  this.sldGroups=[]
  this.sldDynamicGroups=[]
  console.log(this.selectedEmail)
  console.log(value);
  this.isComposeOpen=false
  this.getDGFilters();
  var date=this.datePipe.transform(this.selectedEmail.Date, "yyyy-MM-dd")

  if(this.selectedEmail.ThreadID!=null){
    this.ThreadID=this.selectedEmail.ThreadID
  }
  else{
    this.ThreadID=null
  }
console.log(this.selectedEmail.RecieverXIDs);
console.log(this.selectedEmail);

let senderDetail
//let sldRecieverXID=this.selectedEmail.RecieverXIDs.split(',');
////if(this.messageType=="Sent"){
  if (Array.isArray(this.selectedEmail.RecieverXIDs) && this.selectedEmail.RecieverXIDs.length !== 0) {
  this.receiverIDS=[]
for(let i of this.selectedEmail.RecieverXIDs){ 
if(i.RecieverXID!=this.userID){
console.log(i.RecieverFirstName)
this.receiverIDS.push(i.RecieverXID); 

senderDetail = {
  XID: i.RecieverXID,
  firstName: i.RecieverFirstName,
  value:"replyforward",
  RecieverProfilePicture:i.RecieverProfilePicture
};
this.sldUsers.push(senderDetail);
}
}
if(this.selectedEmail.GroupIDs){
  for(let i of this.selectedEmail.GroupIDs){
    i.GroupType=="Dynamic"?this.sldDynamicGroups.push(i):this.sldGroups.push(i)
  }
}
if(this.selectedEmail.SenderXID!=this.userID){
senderDetail = {
  XID: this.selectedEmail.SenderXID,
  firstName: this.selectedEmail.SenderFirstName,
  value:"replyforward",
  RecieverProfilePicture:this.selectedEmail.SenderProfilePicture
};
this.receiverIDS.push(this.selectedEmail.SenderXID);
this.sldUsers.push(senderDetail);
}
this.messageType == "Replay" ? (this.message = "") : null;
this.isOrginalMessageActive = true;

//--------------------------------------------------------------------------------
// Check Type Forward Here

this.messageType == "Forward"
? ((this.sldUsers=[]),(this.sldGroups=[]),(this.sldDynamicGroups=[]),(this.inboxmessageType=''))
: null;
}
//}
else{
  this.sldUsers=[]
  if(this.selectedEmail.GroupIDs){
    for(let i of this.selectedEmail.GroupIDs){
      i.GroupType=="Dynamic"?this.sldDynamicGroups.push(i):this.sldGroups.push(i)
    }
  }
  // this.receiverIDS=[]
  // senderDetail = {
  //   XID: this.selectedEmail.SenderXID,
  //   firstName: this.selectedEmail.SenderLastName,
  //   value:"replyforward"
  // };
  
  // this.sldUsers.push(senderDetail);
  this.messageType == "Replay" ? (this.message = "") : null;
  this.isOrginalMessageActive = true;
  
  //--------------------------------------------------------------------------------
  // Check Type Forward Here
  
  this.messageType == "Forward"
  ? ((this.sldUsers=[]),(this.sldGroups=[]),(this.sldDynamicGroups=[]),(this.inboxmessageType=''))
  : this.receiverIDS.push(this.selectedEmail.SenderXID);

}

 console.log(this.receiverIDS);
 // return false;
  this.senderdetails=""
  this.content=""
this.inboxmessageType=''
//------------------------------------------------------------------------
// Show Content , Subject and Date in Replay Time and Forward Time

  this.senderdetails=date +  "|" + this.selectedEmail.Time + "," 
  + this.selectedEmail.SenderFirstName + " " + this.selectedEmail.SenderLastName

  this.content=this.selectedEmail.Message.split(" , ")
    
  this.isopendiv=true;
  this.IsReply = 1;

//--------------------------------------------------------------------------------
// Check Type Replay Here 
// In To field show User and Group List if its there otherwise not shown

 

  this.getInboxMailCount();
  console.log(this.sldUsers);
  
  
}


// -------------------------------------------------------------------------------------------------------------------
/**
   * ~ removeOriginalMessage
   *  Show Oriinal Message in Replay and Forward
   * # Method
*/
  removeOriginalMessage() {
    this.IsReply = 0;
    this.isOrginalMessageActive = false;
  }

// --------------------------------------------------------------------------------------------
/**
   * @method Method
   * @name   typeofmessage() 
   * @description click apart from to filed QV should close   
   * Call Toggle Close QV
*/

typeofmessage(value) {
    console.log(value);
    this.isType = value;
    if (this.isType == "To") {
     // this._service.toggleViewCommunication("value", "open","null");
    } else {
      this.closeCommunicationQuickView();
    }
    this.saveCursorPosition()
}

//-----------------------------------------------------------------------------------------------------
/**
   * @updateReadMessage
   * @Get Inbox Message count
   * Method
   * Read Inbox Count API updatereadmessage
*/
updateReadMessage() {
    const url =
      this.notificationURL +
      "notifications/updatereadmessage/" +
      this.selectedEmail.MessageID +
      "/" +
      this.userID +"/"+ this.XBID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res)
      this.unreadCount = res.Count;
     
    });

}
//----------------------------------------------------------------------------------------------------------------------

/**
  * getDGFilters
  * Get DG Filters for Compose
  * Method
  * GET API getdgfiltertypes
*/

getDGFilters() {
    const url = this.notificationURL + "notifications/getdgfiltertypes";
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      this.dgFilters = res;
    
     this.dgFilters.pop()
    });
    this.isAllSelected==false
}


//----------------------------------------------------------------------------------------------------------------------
//1. Active 2. Just Joined 3. Just renewed 4. Renewing soon 5. Expiring soon 6. Just Expired 7. Expired 8. Leads 9. Prospects 10. All

/**
   * ~ getDGFilters
     Get DG Filters for Compose
   * # Method
     * 1 2 3 4 5 6 All,Just Joined, Just Expired, Renewing Soon,etc..
*/
selectedDGFilter(filter, event) {

  console.log(filter);
  this.isType = "DGFilter";
  const checked = event.target.checked;
 // this.toggler.toggleQuickViewChat("Close");
  console.log(this.sldDGFilters);

//----------------------------------------------------------------------------------
// Checked Checkbox 

if (checked) {

//----------------------------------------------------------------------------------
// Check DGFilterTypeID 1 and store into array

       if (filter.DGFilterTypeID === 1) {
       
        this.sldDGFilters.push(filter.DGFilterTypeID);
      }
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 2 and store into array

      else if (filter.DGFilterTypeID === 2) {
       
        this.sldDGFilters.push(filter.DGFilterTypeID);
      } 
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 3 and store into array      

      else if (filter.DGFilterTypeID === 3) {
        
        this.sldDGFilters.push(filter.DGFilterTypeID);
      } 
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 4 and store into array  

      else if (filter.DGFilterTypeID === 4) {
       
        this.sldDGFilters.push(filter.DGFilterTypeID);
      } 
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 5 and store into array      

      else if (filter.DGFilterTypeID === 5) {
        
        this.sldDGFilters.push(filter.DGFilterTypeID);
      }
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 6 and store into array

    else if (filter.DGFilterTypeID === 6) {
        
        this.sldDGFilters.push(filter.DGFilterTypeID);
    }
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 7 and store into array

    else if (filter.DGFilterTypeID === 7) {
        
        this.sldDGFilters.push(filter.DGFilterTypeID);
    }
  } 
//----------------------------------------------------------------------------------
// Else unChecked Checkbox    
 else {
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 1 and remove from array

      if (filter.DGFilterTypeID === 1) {
        
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      }
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 2 and remove from array

     else if (filter.DGFilterTypeID === 2) {
        
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      } 
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 3 and remove from array   

      else if (filter.DGFilterTypeID === 3) {
       
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      } 
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 4 and remove from array    

      else if (filter.DGFilterTypeID === 4) {
        
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      } 
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 5 and remove from array      
      else if (filter.DGFilterTypeID === 5) {
        
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      }
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 6 and remove from array      
      
      else if (filter.DGFilterTypeID === 6) {
        
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      }
//----------------------------------------------------------------------------------
// Check DGFilterTypeID 7 and remove from array

      else if (filter.DGFilterTypeID === 7) {
        
        this.sldDGFilters = this.sldDGFilters.filter((obj) => obj != filter.DGFilterTypeID);
      }

    }
    console.log(this.sldDGFilters)
  }


//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ removeUser
     Remove Selected user from To list and sending Request Service Unselect from Quick View
   * # Method
   */

removeUser(user) {
   
    console.log(user);
    console.log(this.sldUsers)

// Removing user from To list Using getElementBy Id
//------------------------------------------------------------------
    let userXID="user"+user.XID;
    console.log(userXID)
    var a=(<HTMLInputElement>document.getElementById("list"));
    var item=(<HTMLInputElement>document.getElementById(userXID));
     a.removeChild(item);

// Remove Selected User From SldUSers Array 
//------------------------------------------------------------------

     this.sldUsers= this.sldUsers.filter((obj) => obj.XID != user.XID);
     this.sldUsersGroupsList= this.sldUsersGroupsList.filter((obj) => obj.XID != user.XID);
     this.sldUsersForUserCard= this.sldUsersForUserCard.filter((obj) => obj.XID != user.XID);
  // Flatten to make a single array
  this.activeSendbtnList = [].concat.apply([], this.activeSendbtnList);
  this.activeSendbtnList = this.activeSendbtnList.filter((obj) => obj.XID !== user.XID);
  
     console.log("After:", this.activeSendbtnList);
    
     this.receiverIDS= this.receiverIDS.filter((obj) => obj!= user.XID);

// Call Service File And send removed data via Service File To QV Component      
//------------------------------------------------------------------   

  this.unselectUser = {
    userXID:user.XID,
    elementId: userXID,
    type: "remove",
  };
    
   console.log(this.sldUsers) 
   console.log(this.activeSendbtnList) 
   this._service.removeSelectedUsers(this.unselectUser);  
   console.log(this.receiverIDS);
}

//----------------------------------------------------------------------------------------------------------------------  
  /**
   * ~ removeGroup
     Remove group from the Selected List
   * # Method
   */
removeGroup(grp) {
    console.log(grp)
    console.log(this.sldGroups)

// Remove Selected group From sldGroups Array 
//------------------------------------------------------------------

    this.sldGroups = this.sldGroups.filter((obj) => obj.groupID != grp.groupID);
    this.activeSendbtnList= this.activeSendbtnList.filter((obj) => obj.groupID != grp.groupID);
    this.sldUsersGroupsList = this.sldUsersGroupsList.filter((obj) => obj.groupID != grp.groupID);

// Call Service File And send removed data via Service File To QV Component      
//------------------------------------------------------------------       
    this.unselectGroups = {
    groupName:grp.groupName,
    groupType:grp.groupType,
    groupID:grp.groupID,
    type: "remove",
    };
    
   this._service.removeSelectedGroups(this.unselectGroups);

}


//----------------------------------------------------------------------------------------------------------------------
/**
  * ~ removeDynamicGroup
  * Remove DynamicGroup from the Selected List
  * # Method
*/
  
removeDynamicGroup(grp){
    console.log(grp)
    console.log(this.sldDynamicGroups)

    this.sldDynamicGroups.length==1?((this.sldDynamicGroups=[]),(this.isDynamicGroup=false)):null

// Remove Selected Dynamic group From sldDynamicGroups Array 
//------------------------------------------------------------------    

    this.activeSendbtnList= this.activeSendbtnList.filter((obj) => obj.groupID != grp.groupID);
    this.sldDynamicGroups = this.sldDynamicGroups.filter((obj) => obj.groupID != grp.groupID);
    this.sldUsersGroupsList = this.sldUsersGroupsList.filter((obj) => obj.groupID != grp.groupID);

// Call Service File And send removed data via Service File To QV Component      
//------------------------------------------------------------------       

    let unselectDynamcGroups = {
    groupName:grp.groupName,
    groupType:grp.groupType,
    groupID:grp.groupID,
    planGroupId:grp.PlanGroupID,
    type: "remove",
    Type:grp.Type,
    };
    
   this._service.removeSelectedDynamicGroups(unselectDynamcGroups);

  }

//----------------------------------------------------------------------------------------------------------------------


/**
   * ~ onCheckMessage
     Select Message For Delete
   * # Method
   * @param(selected msg, event)
*/
onCheckMessage(item, event) {
  const checked = event.target.checked;
  item.checked = checked; // Update UI state

  const deleteForFolderMessage = {
    MessageID: item.MessageID,
    Source: item.Source,
  };

  if (checked) {
    this.selectedMessageIDs.add(item.MessageID);

    // Avoid duplicate entries
    if (!this.sldFolderMseageDetailsForDelete.some(obj => obj.MessageID === item.MessageID)) {
      this.sldFolderMseageDetailsForDelete.push(deleteForFolderMessage);
    }
  } else {
   this.selectedMessageIDs.delete(item.MessageID);
    this.sldFolderMseageDetailsForDelete = this.sldFolderMseageDetailsForDelete.filter(obj => obj.MessageID !== item.MessageID);
    //this.selectedMessageIDs = this.selectedMessageIDs.filter(obj => obj.MessageID !== item.MessageID);
  }

  // Update the selection arrays
  this.sldMsgIDS = Array.from(this.selectedMessageIDs);

  // **Check if all items on the current page are selected**
  this.isAllSelected = this.getPaginatedDataForList().every(item => item.checked);
  this.updateSelectAllState()

  console.log("Selected Message IDs:", this.sldMsgIDS);
  console.log("Selected Folder Messages for Deletion:", this.sldFolderMseageDetailsForDelete);
}
//this.sldMsgIDS
//this.sldFolderMseageDetailsForDelete
//this.selectedMessageIDs
/**
   * ~ onAllCheckMessage
     Select Message For Delete
   * # Method
   * @param(selected msg, event)
*/




onAllCheckMessage(event) {
  // isAllSelectedCheckbox  //before it was set for folder selectAll
  const checked = event.target.checked;
  this.isAllSelected = checked; // Update select-all state
  let currentPageItems
  // Get paginated items only
  
  if(this.messageType=="List"){
    currentPageItems = this.getPaginatedDataForList();
  }
 else{
   currentPageItems = this.getPaginatedData();
 }

 
  if (!checked) {
    // If "Select All" is unchecked, remove only current page items from selection
    currentPageItems.forEach(item => {
      item.checked = false;
      this.selectedMessageIDs.delete(item.MessageID);
      this.sldFolderMseageDetailsForDelete = this.sldFolderMseageDetailsForDelete.filter(obj => obj.MessageID !== item.MessageID);
    });
  } else {
    // If "Select All" is checked, add all current page items to selection
    currentPageItems.forEach(item => {
      item.checked = true;
      this.selectedMessageIDs.add(item.MessageID);

      const deleteForFolderMessage = {
        MessageID: item.MessageID,
        Source: item.Source,
      };

      // Avoid duplicate entries
      if (!this.sldFolderMseageDetailsForDelete.some(obj => obj.MessageID === item.MessageID)) {
        this.sldFolderMseageDetailsForDelete.push(deleteForFolderMessage);
      }
    });
  }

  // Update selected IDs
  this.sldMsgIDS = Array.from(this.selectedMessageIDs);

  console.log("Selected Message IDs:", this.sldMsgIDS);
  console.log("Selected Folder Messages for Deletion:", this.sldFolderMseageDetailsForDelete);
  this.updateSelectAllState()
}


/**
   * isAllSelectedCheckbox
     it checks all selected checkbox
   * # function 
  
*/

isAllSelectedCheckbox(): boolean {
  return this.getPaginatedDataForList().every((item) =>
    this.selectedMessageIDs.has(item.MessageID)
  );
}


// This method returns the paginated data for the list of messages
// getPaginatedDataForList() {
//   // Replace with your actual data fetching logic
//   return this.messages;
// }

deletewindowModel(){
  console.log(this.messageType)
  this.isModalOpenDelete=true
 }
 
/**
   * closewindowModel
     it closes     window
   * # function 
  
*/
 closewindowModel(){
  console.log(this.messageType)
   this.isModalOpenDelete=false
   this.isModalOpenDeleteFolder=false
  }
//----------------------------------------------------------------------------------------------------------------------

/**
  * deleteSelectedInbox
  * Delete Selected Messages
  * Post API deletemessage
*/

deleteSelectedInbox(){
  let source="Inbox"
const url = this.notificationURL + "notifications/deletemessage/" + this.userID + "/" +source;

//------------------------------------------------------
// Call POST API deletemessage

this.apiCall.makePostApiCall(url, this.sldMsgIDS).then((res: any) => {
      console.log(res);

//------------------------------------------------------
// Response is Success

      if (res.Status === "Success") {
        this.notificationService.showNotification("Success","Message successfully deleted.");
        this.isActiveDelete = false;
        this.isActiveCopy=false
        this.messageType = ""
        this.messageType = "List"
        this.selectedEmail = null;
        this.getAllInboxMessages()
       this.closewindowModel()
        this.backToInboxList()
        this.sldMsgIDS=[]
        this.sldFolderMseageDetailsForDelete = [];
        this.backToInboxList()
      }
    });
  
}

/**
   * ~ deleteInboxMessages
     Delete Selected Messages in Sent and draft
   * # Post
*/
  deleteInboxMessages() {

//------------------------------------------------------
// Type Is Sent

  if(this.messageType==="Sent") {
     let source="Sent"
    const url =this.notificationURL + "notifications/deletemessage/" + this.userID + "/" +source;

//------------------------------------------------------
// POST API

  this.apiCall.makePostApiCall(url, this.sldMsgIDS).then((res: any) => {
    console.log(res);
//------------------------------------------------------
// Response is Success
// call Sent API
    if (res.Status === "Success") {
      this.sldMsgIDS=[]
      this.notificationService.showNotification("Success","Message successfully deleted.");
      this.isActiveDelete = false;
      this.isActiveCopy=false
      this.messageType = ""
      this.messageType = "Sent"
      this.selectedEmail = null;
      this.getAllSentMessages()
      this.backToSentList()
      this.closewindowModel()
      this.sldFolderMseageDetailsForDelete = [];
    }
  });

}

//------------------------------------------------------
// Type Is Draft

else {
let source="Draft"
//------------------------------------------------------
// POST API 
    const url =this.notificationURL + "notifications/deletedraftmessage/" + this.userID + "/" +source;
  this.apiCall.makePostApiCall(url, this.sldMsgIDS).then((res: any) => {
    console.log(res);

//------------------------------------------------------
// Response is Success
// call GetALl draft Message API

    if (res.Status === "Success") {
      this.sldMsgIDS=[];
      this.notificationService.showNotification("Success","Message successfully deleted.");
      this.sldFolderMseageDetailsForDelete = [];
      this.isActiveDelete = false;
      this.selectedEmail = null;
      this.isActiveCopy=false
     this.getAllDraftMessages()
     this.closewindowModel()
    this.backToDraftList()
    }
  });

  }
  
}



//----------------------------------------------------------------------------------------------------------------------

/**
   * ~ openCommunicationQuickView
  @Send Data To QV From Card Conractor,Staff,Co-admin,Member
*/

openCommunicationQuickView(value,type){
//   let AllMerge=[]
// AllMerge=(this.sldUsers.concat(this.sldDynamicGroups.concat(this.sldUsersGroupsList)))
// console.log(AllMerge);

console.log(value)
console.log(type)
console.log(this.sldUsers)
console.log(this.sldGroups)
console.log(this.sldDynamicGroups)
console.log(this.sldUsersGroupsList)


//---------------------------------------------
// Default is Closed QV

//this.toggler.toggleQuickViewChat("Close");

  //  let sldUserGroup={
  //    customGroup:this.sldUsersGroupsList,
  //    dynamicGroup:this.sldDynamicGroups
  // }
  let sldUserGroup=this.sldUsersGroupsList.concat(this.sldDynamicGroups)

   //sldUserGroup=this.sldUsersGroupsList.concat(this.sldGroups)
//---------------------------------------------
// QV is Closed and check length of user and Group List 
// if its there send List via Service File into QV 
// Else call Service File Normally

//  if(this.isOpen==false){
 
//   if(this.sldUsers.length == 0 && this.sldUsersGroupsList.length == 0){
 
//    this._service.toggleViewCommunication("value", "open",type);
//   }

//    else{
//     console.log(this.sldUsers)
//     //console.log(this.sldUsers)
//    this._service.toggleViewCommunication(this.sldUsers, "open",sldUserGroup);
//    }

//   }

  
setTimeout(() => {
  if (!this.isOpen) {
      if (this.sldUsers.length === 0 && this.sldUsersGroupsList.length === 0) {
          this._service.toggleViewCommunication("value", "open", type);
      } else {
          this._service.toggleViewCommunication(this.sldUsers, "open", sldUserGroup);
      }
  }
}, 1) 
  
}

//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ openCommunicationQuickViewGroup
  @Send Data To QV From List Componsnts GROUP VIEW
*/

openCommunicationQuickViewGroup(grp,type){
  console.log(grp)
  console.log("Group Mode Start")
  console.log(this.sldDynamicGroups)
  console.log(this.sldUsersGroupsList)

  let sldUserGroup= {
      customGroup:this.sldUsersGroupsList,
      dynamicGroup:this.sldDynamicGroups
  }

//---------------------------------------------
// QV is Closed and check length of Group List 
// if its there send List via Service File into QV 
// Else call Service File Normally

  if(this.sldDynamicGroups.length===0 && this.sldUsersGroupsList.length===0){
    
   this._service.toggleViewCommunicationGroup("value", "open",type);
   }

   else{
  
    this._service.toggleViewCommunicationGroup(sldUserGroup, "open",type);
   }
}

//----------------------------------------------------------------------------------------------------------------------

/**
   * ~ openCommunicationQuickView
  @Send Data To QV From Card Conractor,Staff,Co-admin,Member
*/

openCommunicationQuickViewForUserCard(userinfo){
  console.log(userinfo)

//---------------------------------------------
// Its Coming From User Card Staff,Member etc... 
// Call QV

if(this.sldUsersForUserCard !=null){
 //   this._service.toggleViewCommunication(this.sldUsersForUserCard, "open","null");
  }
  else{
 //   this._service.toggleViewCommunication("value", "open","null");
  }

}


//----------------------------------------------------------------------------------------------------------------------
/**
  * ~ closeCommunicationQuickView
  *Close  QV From Card Conractor,Staff,Co-admin,Member 
*/

closeCommunicationQuickView(){
  this.isOpen = false;
// this._service.toggleViewCommunication("value", "close","null");
}

//----------------------------------------------------------------------------------------------------------------------
/**
  *openSlide
   Open QV 
*/
openSlide() {
  console.log(this.messageTempID)
  let value
  this.messageTempID==undefined?value=0:value=this.messageTempID
    this.isOpen = false;
   // this._service.toggleViewCommunication("value", "close","null");
   this.closeQuickToggle();
   this._service.toggleViewTemplate(value, "open");
}

// openSlide() {
//   this.isOpen = false;
//  // this._service.toggleViewCommunication("value", "close","null");
//  this.closeQuickToggle();
//  this._service.toggleViewTemplate("value", "open");
// }

//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ closeSlide
  Close QV 
   
*/
closeSlide() {
   // this._service.toggleViewCommunication("value", "close","null");
  //  this._service.toggleViewTemplate("value", "close");
}

//----------------------------------------------------------------------------------------------------------------------

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  SUB- METHODS
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


/**
  * ~ selectedMessageType
  selected Message Type
  List , Sent , Compose
  * Selection Menu and check value type and Call respected data
*/

selectedMessageType(value) {
  this.searchText=''
  this.getFolderList();
  this.selectedFiles=[];
   console.log(value)
   this.itemIsRead=false;
    this.selectedfolderid=""
    this.isDynamicGroup=false;
    this.isopendiv = false;
    this.isActiveCopy=false;
    this.isActiveDelete=false;
    this.sldUsers=[]
    this.sldUsersGroupsList = []
    this.receiverIDS=[]
    this.sldFolderID=null
    this.isActiveDeleteFolder=false;
    this.isActiveEdit=false;
    this.isActiveAdd=true;
    this.currentPage=1;
    this.sldFolderMseageDetailsForDelete=[]
    this.selectedFiles=[]
    this.sldMsgIDS=[]
this.sldFolderMseageDetailsForDelete=[]
//this.selectedMessageIDs=[]
//------------------------------------------------------------------
// Type is List

  value === "List" 
  ? ((this.messageType = "List"),(this.inboxmessageType = 'List'),this.getAllInboxMessages(),this.getPaginatedDataForList(),
  (this.sldMsgIDS = []),(this.isComposeOpen = false),(this.selectedEmail = null),(this.sldDGFilters = []),(this.backToInboxList())
, (this._service.toggleViewCommunication("value", "close","type")))
//------------------------------------------------------------------
// Type is Sent

  : value === "Sent"
  ? ((this.messageType = "Sent"),(this.inboxmessageType =""),this.getAllSentMessages(),(this.sldMsgIDS = []),
  (this.isComposeOpen = false),(this.selectedEmail = null),(this.sldDGFilters = []),(this.backToSentList()), (this._service.toggleViewCommunication("value", "close","type")))

//------------------------------------------------------------------
// Type is Draft

  :value==="Draft"
  ? ((this.messageType = "Draft"),(this.inboxmessageType =""),(this.getInboxMailCount()),(this.getDGFilters()),
  (this.getAllDraftMessages()) ,
  (this.sldMsgIDS = []),
  (this.isComposeOpen = false),
  (this.selectedEmail = null),
  (this.sldDGFilters = []), (this._service.toggleViewCommunication("value", "close","type")))

//------------------------------------------------------------------
// Type is Trash

:value==="Trash"
? ((this.messageType = "Trash"),(this.inboxmessageType =""),(this.getAllTrashMessages()),(this.isTrashOpen=false),
(this.sldMsgIDS = []),
(this.isComposeOpen = false),
(this.selectedEmail = null),
(this.sldDGFilters = []), (this._service.toggleViewCommunication("value", "close","type")))
//------------------------------------------------------------------
// Else is Compose

  :((this.isComposeOpen = true),(this.getInboxMailCount()),(this.getDGFilters()),(this.IsLSPlus=1),
  (console.log("compose window open")),(this.inboxmessageType = ""),(this.messageType = "compose"),(this.isOpenDraft=false),
  (this.itemIsRead = false),(this.isSentSelected=false),(this.subject = ""),(this.subjecttitle=""),(this.isSaveDraft=false),
  (this.message = ""), (this.custommessage=""), (this.content=""), (this.updateSendButtonState()),
  (this.dearuser=""),(this.bodytext=""),(this.bestregards=""),(this.sign=""),
  (this.selectedEmail = null),(this.activeSendbtnList=[]),(this.sldDGFilters = []),
  console.log(this.isComposeOpen == true && this.isOpenDraft==false),console.log('comp'),
  (this.sldDynamicGroups=[]),(this.sldGroups=[]),(this.msgTemplateId=0),(this._service.toggleViewCommunication("value", "close","type")))
  
}

//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ selectedmail
   Flag Settings False dynamic Group and open div 
*/

selectedmail() {
    this.isDynamicGroup=false;
    this.isopendiv = false;
         
}
  //----------------------------------------------------------------------------------------------------------------------

/**
  * ~ openQuickToggle
  * Call QV Open
*/

openQuickToggle() {
    console.log("dooh");
    this.isDisabledinput = false;
    this.isType = "To";
    this.closeSlide();
   // this.toggler.toggleQuickViewMessage("communication");
}


//----------------------------------------------------------------------------------------------------------------------
/**
  * ~ closeQuickToggle
  QV Close
*/

closeQuickToggle() {
  //  this.toggler.toggleQuickViewMessage("close");
}

resetFields() {
  this.subjecttitle = '';
  this.bodytext = '';
  this.dearuser = '';
  // Reset other fields as needed
}
//---------------------------------------------------------------------------------------------------------------------- 

/**
   * ~ cancelMessage
    Cancel Send message 
    Local Storage Remove userdetails
    Close Compose ,reply or fowrd and Draft window
*/

cancelMessage() {
// Array subscription is empty
//---------------------------------------------------  
    this.subscription = [];
    this.activeSendbtnList=[]
    this.msgTemplateId=0
    this.messageTempID= 0;
// SldUserList Remove and make it 0
//---------------------------------------------------
  while (this.sldUsers.length > 0) {
      this.sldUsers.pop();
   } 

// Remove Mentiond Local Storage data
//---------------------------------------------------  
  this.sldUsersForUserCard=null
  localStorage.removeItem("mailUserinfo");
  localStorage.removeItem("userDetailslist")
  this.messageType = "List";
   
// All the Stored variables and arrays are empty
//---------------------------------------------------  
   this.selectedMessageType(this.messageType) 
    this.isComposeOpen=false
    this.isMailcomingfromusercard=false;
    this.subject = "";
    this.subjecttitle = "";
    this.message = "";
    this.dearuser="";
    this.bodytext="";
    this.bestregards="";
    this.sign="";
    this.custommessage=""
    this.isopendiv = true
    this.sldUsersAndGroups = {
      users: [],
      groups: [],
    };
    this.sldUsers = [];
    this.sldGroups = [];
    this.sldDGFilters=[]
    this.sldDynamicGroups=[]
    this.sldUsersGroupsList=[]
    this.isDynamicGroup = false;
    this.sldUsersmail=[]

// Call QV Close
//---------------------------------------------------   
   // this._service.toggleViewCommunication("value", "close","null");

}


//----------------------------------------------------------------------------------------------------------------------
/**
  * ~ gotoTemplate
  Navigate template 
*/
gotoTemplate() {
    this.cancelReplay();
    console.log("inside");
    this.router.navigateByUrl("/notification/template");
   // this.router.navigate(["/notification/template"]
}
//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ cancelReplay
     Clear all message,subject,users,dynamicgroups,
   * # Method
   * QV Close
*/

cancelReplay() {

// All the Stored variables and arrays are empty
//--------------------------------------------------- 

    this.subject = "";
    this.subjecttitle = "";
    this.message = "";
    this.dearuser="";
    this.bodytext="";
    this.bestregards="";
    this.sign="";
    this.msgTemplateId=0
    this.sldUsersForUserCard=null
    this.custommessage=""
    this.messageType = "List";
    this.sldUsers = [];
    this.sldDGFilters=[]
    this.sldDynamicGroups=[];
    this.sldGroups=[]
    this.receiverIDS = [];
    const grpsandusers = {
      users: [],
      groups: [],
    };

// Check TYpe and Call API either List or Sent
//--------------------------------------------------- 

  // if(

  
    this.inboxmessageType=="List"

  // ){
      
    this.selectedMessageType('List')
  // }
  // else{
  //     this.selectedMessageType('Sent')
  // }
    this.isDynamicGroup = false;
   // this.quickViewSVC.addUser(grpsandusers);

// Call QV Close
//---------------------------------------------------     
   // this._service.toggleViewCommunication("value", "close","null");
    this.activeSendbtnList=[]
}


//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ includeMailMenthod
     Select Include message
   * # Method
   */
  includeMailMenthod(event) {
    const checked = event.target.checked;
    if (checked) {
      this.isIncludeMail = true;
    } else {
      this.isIncludeMail = false;
    }
  }

//----------------------------------------------------------------------------------------------------------------------

/**
   * getInboxMailCount
     Get Inbox Message count
   * # GET API getInboxMailCount
     Check and Display Remaining Email Count and Quotes 
     Display In Compose window
*/
getInboxMailCount() {
    this._service.getInboxMailCount(this.XBID).subscribe((res: any) => {
      console.log(res);
      this.emailQuotes = res.EmailQuotes;
      this.emailRemaining = res.EmailRemaining;
    });
}
//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ updateViewCount
     Update View Count
   * # GET API updateviewcount
     Update Inbox Mesage Viwed count
*/
updateViewCount() {
    const url =
      this.notificationURL +
      "notifications/updateviewcount/" +
      this.selectedEmail.MessageID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res)
    });
}

//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------

containsCurlyBraces(): boolean {
  return this.message.includes('{}');

}
/**
   * ~ sendDraftMessage
    SEND Draft Message
   * # POST
*/
sendDraftMessage(value) {

   // console.log(value)
   // this.IsDraft=value
    console.log(this.IsDraft);  
    console.log(this.draftID)
    //return 
    console.log(this.sldGroups)
    console.log(this.sldUsers)
    let grpUIDS = [];
    let dgruids=[]
    let userIDS = [];
    let groupIDs = [];
    if(this.messageIndex==undefined){
      this.messageIndex=null
    }
    if(this.messageTempID==undefined){
      this.messageTempID=null
    }
// checking XID's and Group Id's For Groups
//----------------------------------------------------
// Check dynamic Group XID's 

    this.sldGroups != undefined
      ? 
      (this.sldGroups.map((obj) => {
      // // obj.XIDS.map((k) => {
      //       //grpUIDS.push(k);
      //   //  });
        }),

//----------------------------------------------------
// Check Group GroupId's 

        this.sldGroups.map((obj) => {
          groupIDs.push(obj.groupID);
        }),
        console.log(groupIDs))
      : null;

//----------------------------------------------------
// Check dynamic Group XID's 

      this.sldDynamicGroups != undefined
      ? (this.sldDynamicGroups.map((obj) => {
         // obj.XIDS.map((k) => {
           
         // });
     }),

// checking XID's and Group Id's For Dynamic Groups
//-------------------------------------------------------------------------------
        this.sldDynamicGroups.map((obj) => {
          groupIDs.push(obj.groupID);
          dgruids.push(obj.groupID);
        }),
        console.log(groupIDs))
      : null;

// checking XID's and Group Id's For Users
//-------------------------------------------------------------------------------
   if(this.sldUsers!=undefined) {
    this.sldUsers.map((us) => {
      userIDS.push(us.XID);
    //  this.receiverIDS.push(us.XID)
    });
   }
   
   
//-------------------------------------------------------------------------------    
//-------------------------------------------------------------------------------
//receiver XIDs except dg groups 
// this.receiverIDS = [...grpUIDS, ...userIDS];

    console.log(this.receiverIDS);
    console.log("**********");
  
// checking DG Filters
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------

    let dgFilters = "";
    this.sldDGFilters.length != 0
      ? (dgFilters = this.sldDGFilters.toString())
      : this.isDynamicGroup == true
      ? (dgFilters = null)
      : (dgFilters = "10");


    const remainingcount = this.emailRemaining - userIDS.length;
    const newDate = new Date();
    const currentTime = this.datePipe.transform(newDate, "h:mm a");


    const url = this.notificationURL + "notifications/managemessage";

// checking MEssage Template ID
//-------------------------------------------------------------------------------
console.log(this.msgTemplateId )


//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
if(this.msgTemplateId !=0){
  this.message=""
  this.message = document.getElementById("texteditor").innerText;
  //this.containsCurlyBraces();
 }
 if(this.msgTemplateId==0 || this.msgTemplateId==undefined){
   var editermessage = document.getElementById("texteditor").innerText;
    console.log(editermessage);
    this.message=""
    this.message=editermessage;
   // this.containsCurlyBraces();
  }

// if(this.containsCurlyBraces()){\
if(this.message.match(/{([^}]+)}/g)){
  this.isDynamicText=1
 }
 else{
  this.isDynamicText=0
 }

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
    const UserDeatils = {
      SenderXID: this.userID,
      SenderXBID: this.XBID,
      RecieverXIDs: this.receiverIDS.toString(),
      GroupIDs: groupIDs.toString(),
      DGGroupIDs:dgruids.toString(),
      RecieverXBIDs: [this.XBID].toString(),
      Subject: this.subjecttitle,
      Message: this.message,
      Date: this.datePipe.transform(newDate, "yyyy-MM-dd"),
      Time: currentTime,
      IsReply: 0,
      IsTrash:0,
      IsDraft:0,
      Whatsapp: this.isCheckInclude,
      IncludeMail: this.isWhatsapp,
      IsLSPlus:this.IsLSPlus,
     // Whatsapp: this.isWhatsapp,
      RemainingEmailCount: remainingcount,
      DGFilters: dgFilters,
      MessageID:this.draftID,
      IsDynamicFields:this.isDynamicText,
      ThreadID :null,
      Code:this.messageIndex,
      MessageTempltID :this.messageTempID 
    };


    console.log(UserDeatils);

    // API CAll
    // POST------------------------------------------------------

    this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
      console.log(res);

      if (res.Status === "Success") {
        while (this.sldUsers.length > 0) {
          this.sldUsers.pop();
          this.receiverIDS=[]
      } // Fastest

      this.notificationService.showNotification("Success","Message successfully sent.");
        this.sldMsgIDS=[]
        this.sldMsgIDS.push(this.draftID)


//-------------------------------------------------------------------------------       
//-------------------------------------------------------------------------------
// once send is success delete draft message
//POST API deletedraftmessage

  // const url =this.notificationURL + "notifications/deletedraftmessage/" + this.userID;
  //   this.apiCall.makePostApiCall(url, this.sldMsgIDS).then((res: any) => {
  //   console.log(res);

// Response Success
// call Draft and Inbox API
//-------------------------------------------------------------------------------          
  //  if (res.Status === "Success") {
    this.sldMsgIDS=[]
    this.isActiveDelete = false;
    this.selectedEmail = null;
    this.isActiveCopy=false
    this.selectedMessageType("Draft");
    this.getAllDraftMessages()
    //this.getAllSentMessages()
    this.isDynamicText=0  
    this.isDynamicGroup = false;
    this.sldUsers=[];
    this.custommessage=""
    this.sldGroups=[];
    this.sldDGFilters=[]
    this.sldDynamicGroups=[]
    this.sldUsersmail=[]
    this.subscription = [];
    this.isComposeOpen=false
    this.isMailcomingfromusercard=false;
    this.sldUsersGroupsList=[]
    this.sldUsersForUserCard=null
    localStorage.removeItem("mailUserinfo");
    this.msgTemplateId=0
    this.messageTempID=null
    this.messageIndex=null
  //   } // Delete Success condin End here
  // });// Delete Draft API End 
          
  }// Send draft Suceess MSg Condition End here 

  });// Send draft Msg End here
}// function close

//----------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------- 

//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ sendComposeMessage
     Send Message to the selected Users
   * # POST
*/
  sendComposeMessage(value) {
    console.log(value)
    console.log(this.messageIndex)
    console.log(this.messageTempID)
    if(this.messageIndex==undefined){
      this.messageIndex=null
    }
    if(this.messageTempID==undefined){
      this.messageTempID=null
    }
    
    this.IsDraft=value
    console.log(this.IsDraft);
    console.log(this.sldGroups)
    console.log(this.sldGroups)
    console.log(this.sldUsers)
    let grpUIDS = [];
    let dgruids=[]
    let userIDS = [];
    let groupIDs = [];
    let Attachments=[]
// checking XID's and Group Id's For Groups
//---------------------------------------------------------------------
    this.sldGroups != undefined
      ? 
      (this.sldGroups.map((obj) => {
      // // obj.XIDS.map((k) => {
      //       //grpUIDS.push(k);
      //   //  });
        }),
        this.sldGroups.map((obj) => {
          groupIDs.push(obj.groupID);
        }),
        console.log(groupIDs))
      : null;

      this.sldDynamicGroups != undefined
      ? (this.sldDynamicGroups.map((obj) => {
          // obj.XIDS.map((k) => {
          //  //grpUIDS.push(k);
          //  // dgruids.push(k)
          // });
        }),

// checking XID's and Group Id's For Dynamic Groups
//---------------------------------------------------------------------
        this.sldDynamicGroups.map((obj) => {
          groupIDs.push(obj.groupID);
          dgruids.push(obj.groupID);
        }),
        console.log(groupIDs))
      : null;

// checking XID's and Group Id's For Users
//---------------------------------------------------------------------
   if(this.sldUsers!=undefined) {
    this.sldUsers.map((us) => {
      userIDS.push(us.XID);
    //  this.receiverIDS.push(us.XID)
    });
   }
   
    console.log("**********");
    console.log(grpUIDS);
    console.log(userIDS);
    

//receiver XIDs except dg groups 
//---------------------------------------------------------------------
// this.receiverIDS = [...grpUIDS, ...userIDS];
    console.log(this.receiverIDS);
    console.log("**********");
    console.log(this.receiverIDS.toString());

// checking DG Filters
//---------------------------------------------------------------------
    let dgFilters = "";
    this.sldDGFilters.length != 0
      ? (dgFilters = this.sldDGFilters.toString())
      : this.isDynamicGroup == true
      ? (dgFilters = null)
      : (dgFilters = "10");


    const remainingcount = this.emailRemaining - userIDS.length;
    const newDate = new Date();
    const currentTime = this.datePipe.transform(newDate, "h:mm a");


    const url = this.notificationURL + "notifications/managemessage";

// checking MEssage Template ID
//---------------------------------------------------------------------
console.log(this.msgTemplateId )
this.message=""
if(this.msgTemplateId !=0){
  //this.message=this.dearuser+this.bodytext+this.bestregards+this.sign;
  this.message = document.getElementById("texteditor").innerText;
//  this.containsCurlyBraces();
  console.log(this.message)
 }
   if(this.msgTemplateId==0 || this.msgTemplateId==undefined){
   var editermessage = document.getElementById("texteditor").innerText;
    console.log(editermessage);
 
    this.message=editermessage;
   // this.containsCurlyBraces();
    console.log(this.message)
  }
  
  console.log(this.message)

 // if(this.containsCurlyBraces()){
  if(this.message.match(/{([^}]+)}/g)){
    this.isDynamicText=1
    console.log(this.isDynamicText)
   }
   else{
    this.isDynamicText=0
    console.log(this.isDynamicText)
   }

   // Checking files 
   if(this.selectedFiles.length!=0){
  for(let i of this.selectedFiles)
{
  let attachedInfo={
    filename:i.filename,
    filetype:i.filetype,
    data:i.url,
  }
  Attachments.push(attachedInfo)
}
  }

   // checking files 

    const UserDeatils = {
      SenderXID: this.userID,
      SenderXBID: this.XBID,
      RecieverXIDs: this.receiverIDS.toString(),
      GroupIDs: groupIDs.toString(),
     DGGroupIDs:dgruids.toString(),
      RecieverXBIDs: [this.XBID].toString(),
      Subject: this.subjecttitle,
      Message: this.message,
      Date: this.datePipe.transform(newDate, "yyyy-MM-dd"),
      Time: currentTime,
      IsReply: 0,
      IsTrash:0,
      IsDraft:this.IsDraft,
      Whatsapp: this.isCheckInclude,
      IncludeMail: this.isWhatsapp,
      IsLSPlus:this.IsLSPlus,
      RemainingEmailCount: remainingcount,
      DGFilters: dgFilters,
      MessageID:null,
      IsDynamicFields:this.isDynamicText,
      Attachments:Attachments,
      ThreadID:null,
      Code:this.messageIndex,
      MessageTempltID :this.messageTempID
    };

// API CAll
// POST------------------------------------------------------

    this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
      console.log(res);

      if (res.Status === "Success") {
        while (this.sldUsers.length > 0) {
          this.sldUsers.pop();
          this.receiverIDS=[]
      } // Fastest
//---------------------------------------------------------------------       
    //  this._service.toggleViewCommunication("value", "close","null");
       if(this.IsDraft==0){
        this.notificationService.showNotification("Success","Message successfully sent.");
          this.selectedMessageType('List')
          this.isDynamicGroup = false;
          this.sldUsers=[];
          this.custommessage=""
          this.sldGroups=[];
          this.sldDGFilters=[]
          this.sldDynamicGroups=[]
          this.sldUsersmail=[]
          this.subscription = [];
          this.isComposeOpen=false
          this.isMailcomingfromusercard=false;
          this.sldUsersGroupsList=[]
          this.sldUsersForUserCard=null
          localStorage.removeItem("mailUserinfo");
          this.msgTemplateId=0  
          this.selectedFiles=[]
            this.messageTempID=""
           this.messageIndex=""
    }
//---------------------------------------------------------------------
    else{
        this.isDynamicText=0
        // this._notification.create("success", "Draft Saved", {
        //   Position: "top-right",
        //   Style: "flip bar",
        //   Duration: 3000,
        // });
        this.notificationService.showNotification("Success","Draft Saved successfully.");
      //  this.getAllDraftMessages()
      this.selectedMessageType('List')
        this.sldUsersForUserCard=null
        this.isDynamicGroup = false;
        this.sldUsers=[];
        this.custommessage=""
        this.sldGroups=[];
        this.sldDGFilters=[]
        this.sldDynamicGroups=[]
        this.sldUsersmail=[]
        this.subscription = [];
        this.isComposeOpen=false
        this.selectedFiles=[]
           this.messageTempID=""
           this.messageIndex=""
//---------------------------------------------------------------------    
//---------------------------------------------------------------------
        localStorage.removeItem("mailUserinfo");
        this.isMailcomingfromusercard=false;
       }
      }

    });
  }

//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------  
// Update Draft 
// POST API
// Sending payload with message ID 
//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
updateDraft() {
  
  this.IsDraft=1
  console.log(this.IsDraft);
  console.log(this.sldGroups)
  console.log(this.sldGroups)
  console.log(this.sldUsers)
  let grpUIDS = [];
  let dgruids=[]
  let userIDS = [];
  let groupIDs = [];
  
// checking XID's and Group Id's For Groups
//-------------------------------------------------------------------------------
  this.sldGroups != undefined
    ? (this.sldGroups.map((obj) => {
        // obj.XIDS.map((k) => {
        //   grpUIDS.push(k);
        // });
      }),
      this.sldGroups.map((obj) => {
        groupIDs.push(obj.groupID);
      }),
      console.log(groupIDs))
    : null;

    this.sldDynamicGroups != undefined
    ? (this.sldDynamicGroups.map((obj) => {
        obj.XIDS.map((k) => {
         //grpUIDS.push(k);
         // dgruids.push(k)
        });
      }),

// checking XID's and Group Id's For Dynamic Groups
//-------------------------------------------------------------------------------
      this.sldDynamicGroups.map((obj) => {
        groupIDs.push(obj.groupID);
        dgruids.push(obj.groupID);
      }),
      console.log(groupIDs))
    : null;

// checking XID's and Group Id's For Users
//-------------------------------------------------------------------------------
 if(this.sldUsers!=undefined) {
  this.sldUsers.map((us) => {
    userIDS.push(us.XID);
  });
 }
 
  console.log("**********");
  console.log(grpUIDS);
  console.log(userIDS);
  

//receiver XIDs except dg groups 
//-------------------------------------------------------------------------------
//this.receiverIDS = [...grpUIDS, ...userIDS];

  console.log(this.receiverIDS);
  console.log("**********");
 
//-------------------------------------------------------------------------------
// checking DG Filters

  let dgFilters = "";
  this.sldDGFilters.length != 0
    ? (dgFilters = this.sldDGFilters.toString())
    : this.isDynamicGroup == true
    ? (dgFilters = null)
    : (dgFilters = "10");


  const remainingcount = this.emailRemaining - userIDS.length;
  const newDate = new Date();
  const currentTime = this.datePipe.transform(newDate, "h:mm a");

//-------------------------------------------------------------------------------
// API Call updatedraftmessage

 const url = this.notificationURL + "notifications/updatedraftmessage";

// checking MEssage Template ID
this.message = document.getElementById("texteditor").innerText;

// checking UserDeatils
//-------------------------------------------------------------------------------


  const UserDeatils = {
    AttachmentPath:this.AttachmentPath,
    MessageID:this.draftID,
    SenderXID: this.userID,
    SenderXBID: this.XBID,
    RecieverXIDs: this.receiverIDS.toString(),
    GroupIDs: groupIDs.toString(),
   DGGroupIDs:dgruids.toString(),
    RecieverXBIDs: [this.XBID].toString(),
    Subject: this.subjecttitle,
    Message: this.message,
    Date: this.datePipe.transform(newDate, "yyyy-MM-dd"),
    Time: currentTime,
    IsReply: 0,
    IsDraft:this.IsDraft,
    Whatsapp: this.isCheckInclude,
    IncludeMail: this.isWhatsapp,
    IsLSPlus:this.IsLSPlus,
    RemainingEmailCount: remainingcount,
    DGFilters: dgFilters,
    ThreadID:null
  };

  // API CAll
  // POST------------------------------------------------------

  this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
    console.log(res);

//-------------------------------------------------------------------------------
// Sucess Response

    if (res.status === "Success") {
      while (this.sldUsers.length > 0) {
        this.sldUsers.pop();
    } // Fastest
    
    
//-------------------------------------------------------------------------------      
    // this._service.toggleViewCommunication("value", "close","null");
   
    //   this._notification.create("success", "Draft Saved", {
    //     Position: "top-right",
    //     Style: "flip bar",
    //     Duration: 3000,
    //   });
    this.notificationService.showNotification("Success","Draft Saved successfully.");
//-------------------------------------------------------------------------------
      this.selectedMessageType("Draft");
      this.isDynamicGroup = false;
      this.sldUsers=[];
      this.custommessage=""
      this.sldGroups=[];
      this.sldDGFilters=[]
      this.sldDynamicGroups=[]
      this.sldUsersmail=[]
      this.subscription = [];
      this.isComposeOpen=false
      this.isMailcomingfromusercard=false;
      this.sldUsersForUserCard=null
      localStorage.removeItem("mailUserinfo");

    } // If condition close here success

  });// API Called End here

} // End Update Draft here


//----------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------
/**
   * @replayMessage
     Replay to the User
   * # POST
*/
  //----------------------------------------------------------------------------------------------------------------------
  //----------------------------------------------------------------------------------------------------------------------
  
replayMessage(value) {
    console.log(value)
    this.IsDraft=value
    console.log("inside");
    let grpUIDS = [];
    let dgruids=[]
    let userIDS = [];
    let groupIDs = [];
    this.activeSendbtnList=[]
    if(this.messageIndex==undefined){
      this.messageIndex=null
    }
    if(this.messageTempID==undefined){
      this.messageTempID=null
    }
// checking XID's and Group Id's For Groups
//---------------------------------------------------------------------
    this.sldGroups != undefined
      ? 
      (this.sldGroups.map((obj) => {
      //  obj.XIDS.map((k) => {
      //       grpUIDS.push(k);
      //     });
        }),
        this.sldGroups.map((obj) => {
          groupIDs.push(obj.groupID);
        }),
        console.log(groupIDs))
      : null;

      this.sldDynamicGroups != undefined
      ? (this.sldDynamicGroups.map((obj) => {
          obj.XIDS.map((k) => {
           //grpUIDS.push(k);
           // dgruids.push(k)
          });
        }),

// checking XID's and Group Id's For Dynamic Groups
//---------------------------------------------------------------------
        this.sldDynamicGroups.map((obj) => {
          groupIDs.push(obj.groupID);
          dgruids.push(obj.groupID);
        }),
        console.log(groupIDs))
      : null;

   if(this.sldUsers!=undefined) {
    this.sldUsers.map((us) => {
      userIDS.push(us.XID);
      
    });
   }
   
    console.log("**********");
    console.log(grpUIDS);
    console.log(userIDS);
//---------------------------------------------------------------------   
//this.receiverIDS = [...grpUIDS, ...userIDS];
    console.log(this.receiverIDS);
    console.log("**********");
   

    // checing DG Filters Value

    let dgFilters = "";
    this.sldDGFilters.length != 0
      ? (dgFilters = this.sldDGFilters.toString())
      : this.isDynamicGroup == true
      ? (dgFilters = null)
      : (dgFilters = "10");

    const remainingcount = this.emailRemaining - userIDS.length;
    const newDate = new Date();
    const currentTime = this.datePipe.transform(newDate, "h:mm a");

// API Call
//---------------------------------------------------------------------
    const url = this.notificationURL + "notifications/managemessage";
    
// checing Template ID's
//---------------------------------------------------------------------
console.log(this.msgTemplateId )
  this.message=""
    if(this.msgTemplateId !=0){
      
      this.message = document.getElementById("texteditor").innerText;
     }
    if(this.msgTemplateId==0 || this.msgTemplateId==undefined){

     var replysubject = document.getElementById("texteditor").innerText;
     //alert(replysubject);
    
     this.message=replysubject
    }
    // if(this.containsCurlyBraces()){\
     if(this.message.match(/{([^}]+)}/g)){
       this.isDynamicText=1
      }
   else{
       this.isDynamicText=0
      }  
//---------------------------------------------------------------------
// POST USer Details

    if(this.IsDraft==0){

    var UserDeatils = {
      SenderXID: this.userID,
      SenderXBID: this.XBID,
      GroupIDs: groupIDs.toString(),
      DGGroupIDs:dgruids.toString(),
      RecieverXIDs: this.receiverIDS.toString(),
      RecieverXBIDs: [this.XBID].toString(),
      Subject: this.subject,
      Message: this.message,
      Date: this.datePipe.transform(newDate, "yyyy-MM-dd"),
      Time: currentTime,
      Whatsapp: this.isCheckInclude,
      IncludeMail: this.isWhatsapp,
      IsLSPlus:this.IsLSPlus,
      IsReply: this.IsReply,
      IsTrash:0,
      IsDraft:this.IsDraft,
      RemainingEmailCount: remainingcount,
      MessageID:null,
      // DGGroupIDs:"",
      DGFilters: dgFilters,
      IsDynamicFields:this.isDynamicText,
      ThreadID:this.ThreadID,
     Code:this.messageIndex,
     MessageTempltID :this.messageTempID

    };
  }
//---------------------------------------------------------------------
//---------------------------------------------------------------------  
  else{
    var UserDeatils1 = {
      SenderXID: this.userID,
      SenderXBID: this.XBID,
      GroupIDs: groupIDs.toString(),
      DGGroupIDs:dgruids.toString(),
     // RecieverXIDs: this.receiverIDS.toString(),
      RecieverXIDs:null,
      RecieverXBIDs: [this.XBID].toString(),
      Subject: this.subject,
      Message: this.message,
      Date: this.datePipe.transform(newDate, "yyyy-MM-dd"),
      Time: currentTime,
      Whatsapp: this.isCheckInclude,
      IncludeMail: this.isWhatsapp,
      IsLSPlus:this.IsLSPlus,
      IsReply: this.IsReply,
      IsDraft:this.IsDraft,
      RemainingEmailCount: remainingcount,
      IsTrash:0,
      // GroupIDs: "",
      // DGGroupIDs:"",
      DGFilters: dgFilters,
      MessageID: null,
      IsDynamicFields:this.isDynamicText,
      ThreadID:this.ThreadID,
      Code:this.messageIndex,
      MessageTempltID :this.messageTempID
    };
    UserDeatils=UserDeatils1
  }
    console.log(UserDeatils);

    // API CAll
    // POST------------------------------------------------------

    this.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
      console.log(res);
      if (res.Status === "Success") {
        this.custommessage=""
        this.sldUsers=[];
        this.isDynamicText=0;
        this.sldGroups=[];
        this.sldDGFilters=[]
        this.sldDynamicGroups=[]
        this.isDynamicGroup = false;
        this.receiverIDS = [];
        this.sldUsersGroupsList=[]
        this.notificationService.showNotification("Success","Message successfully sent.");
        this.sldUsersForUserCard=null
           this.messageTempID=null
           this.messageIndex=null
        if (this.isIncludeMail === true) {
          this.decrementInboxMailCount();
          this.updateReplayMessage();
        }
        this.cancelReplay();
      //  this.router.navigateByUrl("/notification/list");
        this.message = null;
        this.selectedMessageType("List");
       // this.getAllSentMessages()
       // this.getAllDraftMessages()
        this.sldDGFilters=[]
        this.receiverIDS=[]
        this.msgTemplateId=0
      }
    });
  }
//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ updateReplayMessage
     Update Replay Message
   * # GET updatereplymessage
   */
  updateReplayMessage() {
    const url =
      this.notificationURL +
      "notifications/updatereplymessage/" +
      this.selectedEmail.MessageID;
    this.apiCall.makeGetApiCall(url).then((res: any) => {
      console.log(res);
      this.receiverIDS = [];
    });
  }
//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ selectWhatsapp
     Check Whatsapp send notification to mail
   * # Method
   */
  selectWhatsapp(event) {
    const checked = event.target.checked;
    if (checked) {
      this.isCheckInclude = 1;
    } else {
      this.isCheckInclude = 0;
    }
    this.updateSendButtonState();
    console.log(this.isCheckInclude)
  }
//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ selectIncludeMail
   * * Check mail send notification to mail
   * # Method
   */
  selectIncludeMail(event) {
    const checked = event.target.checked;
    if (checked) {
      this.isWhatsapp = 1;
    } else {
      this.isWhatsapp = 0;
    }
    this.updateSendButtonState();
    console.log(this.isWhatsapp)
  }

  selectIncludeLSPlus(event) {
    const checked = event.target.checked;
    if (checked) {
      this.IsLSPlus = 1;
    } else {
      this.IsLSPlus = 0;
    }
    this.updateSendButtonState();
    console.log(this.IsLSPlus)
  }


   
/**
   * ~  updateSendButtonState
   * * Check the upadte send button state
   * # Method
   */

  updateSendButtonState() {
    this.isSendButtonEnabled = this.isCheckInclude === 1 || this.isWhatsapp === 1 || this.IsLSPlus === 1;
    console.log("Send Button Enabled:", this.isSendButtonEnabled);
  }
//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ decrementInboxMailCount
     Get Inbox Message count
   * # GET
   */
  decrementInboxMailCount() {
    this.emailRemaining = this.emailRemaining - 1;
    this.emailQuotes = this.emailQuotes;
    const sendData = {
      EmailQuotes: this.emailRemaining,
      EmailRemaining: this.emailQuotes,
    };
// Decrement Inbox count once we opend new message
//------------------------------------------------------    
    this._service
      .decrementInboxMailCount(this.XBID, sendData)
      .subscribe((res) => {
        console.log(res);
      });
  }



/**
   * @method Method
   * @name getGymRole
   * @description checking restriction type All / notaccess
   * ADD / Edit / Delete / View 
   
*/

getGymRole() {
  const url =this.apiServer +
  "businessacount/getgymroleaccessforuser/" + this.XBID + "/"+ this.userID

  this.apiCall.makeGetApiCall(url).then((res: any) => {
    //console.clear()
    console.log(res)

  for(let i of res){

    if(i.RoleName==this.userDetails.role){
   if(i.Menu=="Communication" && i.Submenu=="Message"){
    this.messgaeAccess=i.AccessLevel; 
   }
   if(i.Menu=="Communication" && i.Submenu=="Group"){
    this.groupAccess=i.AccessLevel; 
   }
   if(i.Menu=="Communication" && i.Submenu=="Template"){
    this.templateAccess=i.AccessLevel; 
   }
  }
  }
   

  });
  
}

//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
// dynamic Text field 

/**
   * @method Method
   * @name onRightClick
   * @description Mouse right click event open QV while writting custom template
*/
onRightClick(event: MouseEvent): void {
 // event.preventDefault(); // Prevent the default context menu from appearing
  console.log('Right-clicked!');
  this.closeCommunicationQuickView();
  this.isOpen=true;
  console.log(this.bodyClass)
  this.bodyClass.add("slideprofile");
  console.log(this.bodyClass)
 
  this.getDynamicListFields();
 //this.sldListDfd=[]
//this.sldDisplayDfd=[]
  // Your custom logic for handling the right-click event goes here
}


//----------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------
/**
   * @method function
   * @name closetoggle
   * @description closetoggle Close QV
*/

closetoggle(){
 this.isOpen=false
 this.bodyClass.remove("slideprofile");
 this.sldListDfd=[]
 this.sldDisplayDfd=[]
}

/**
   * @method function
   * @name getDynamicListFields
   * @description get All dynamic Fields List API-getdynamicfields
*/
getDynamicListFields(){
 //var textAll;
  const url =this.notificationURL +"notifications/getdynamicfields";
  this.apiCall.makeGetApiCall(url).then((res: any) => {
  console.log(res);
 // this.dynamictextAll=res;
 this.dyTextAll=res;
//  if(res.length != 0){
//   this.dynamictextAll=res;
//  }
//  else{
//   this.dynamictextAll=[]
//  }

console.log(this.dyTextAll)
 });


console.log(this.dyTextAll)

}
/**
   * @method function
   * @name onCheckDynamicField
   * @description checkBox Selection and send into text box
*/
onCheckDynamicField(val,event){
  console.log(val);
  const checked = event.target.checked;
  if(checked){
    //this.sldDFID=val.DFID;
    this.sldListDfd.push(val);
    val.checked = true;
    
  }
  else{
    this.sldDFID=null
    const index1 = this.sldListDfd.findIndex(
      (pl) => pl.DFID == val.DFID
      );
      
    this.sldListDfd.splice(index1, 1);
    val.checked = false;
  }
  if(this.sldListDfd.length!=0){
   this.isDynamicText=1
  }
  else{
    this.isDynamicText=0
  }
  console.log(this.sldListDfd)
}


/**
   * @method function
   * @name selectDynamicText
   * @description send button click and send data
*/

selectDynamicText(event){
  this.isOpen=false;
  this.bodyClass.remove("slideprofile");
 console.log(this.sldListDfd)
  this.sldDisplayDfd=[]
 
 this.sldDisplayDfd=this.sldListDfd;
 console.log(this.sldDisplayDfd)
this.sldListDfd=[]
//  let dynamicField = ''; // Replace this with the actual dynamic field value
 if(this.sldDisplayDfd.length !=0){
  for (let i of this.sldDisplayDfd){
   this.insertDynamicField(i.DFTag)
  
  }
 
}
}

/**
   * @method function
   * @name insertTextAtCursor
   * @description insert dynamic text and add span tag and attribute 
*/
 // Insert dynamic field at the saved cursor position
//  insertDynamicField(dynamicField: string): void {
//   console.log(dynamicField);
//   console.log(this.savedRange);
  
//   if (this.savedRange) {
//     const selection = window.getSelection();
//     console.log(selection);
    
//     if (selection) {
//       console.log(selection);
//       selection.removeAllRanges();
//       selection.addRange(this.savedRange);

//       // Create a span element and set its style to bold
//       const span = document.createElement("span");
//       span.style.fontWeight = "bold";
//       span.textContent = dynamicField;

//       // Insert the span element at the cursor position
//       this.savedRange.insertNode(span);

//       // Update the saved range to move the cursor after the inserted text
//       this.savedRange.setStartAfter(span);
//       this.savedRange.setEndAfter(span);

//       // Update the current selection with the new range
//       selection.removeAllRanges();
//       selection.addRange(this.savedRange);

//       // DO NOT clear savedRange here; keep it for the next insert
//     }
//   }
// }

// insertDynamicField(dynamicField: string): void {
//   console.log(dynamicField);
//   console.log(this.savedRange);

//   if (this.savedRange) {
//     const selection = window.getSelection();
//     console.log(selection);

//     if (selection) {
//       selection.removeAllRanges();
//       selection.addRange(this.savedRange);

//       // Create a bold span for the dynamic field
//       const span = document.createElement("span");
//       span.style.fontWeight = "bold";
//       span.textContent = dynamicField;

//       // Insert the span at the cursor position
//       this.savedRange.insertNode(span);

//       // Create a new empty text node after the span
//       const textNode = document.createTextNode("\u00A0"); // Non-breaking space
//       span.after(textNode);

//       // Move the cursor to the new text node
//       this.savedRange.setStartAfter(textNode);
//       this.savedRange.setEndAfter(textNode);

//       // Update selection with the new range
//       selection.removeAllRanges();
//       selection.addRange(this.savedRange);

//       // Keep savedRange for further inserts
//     }
//   }
// }
// insertDynamicField(dynamicField: string): void {
//   if (this.savedRange) {
//     const selection = window.getSelection();
//     if (selection) {
//       selection.removeAllRanges();
//       selection.addRange(this.savedRange);

//       // Create a span element with the "dfield" class
//       // const spanElement = document.createElement("span");
//       // spanElement.classList.add("dfield");
//       // spanElement.textContent = dynamicField; // Set text content
//       const txt=document.createElement('strong')
//       txt.textContent=dynamicField
//       // Insert the span at the cursor position
//       this.savedRange.deleteContents(); // Remove any selected text
//       this.savedRange.insertNode(txt);

//       // Insert a space after the dynamic field to separate it from normal text
//       const space = document.createTextNode(" "); // Space character
//       const space1 = document.createTextNode(" "); // Space character
//       txt.before(space1);
//       txt.after(space);
     
//       // Move the cursor after the space
//       this.savedRange.setStartAfter(space);
//       this.savedRange.setEndAfter(space);

//       // Update the selection
//       selection.removeAllRanges();
//       selection.addRange(this.savedRange);
//     }
//   }
// }
insertDynamicField(dynamicField: string): void {
  if (this.savedRange) {
    const selection = window.getSelection();
    if (selection) {
      selection.removeAllRanges();
      selection.addRange(this.savedRange);

      // Create a strong element for bold text
      const strongElement = document.createElement("strong");
      strongElement.textContent = dynamicField;

      // Insert the bold text at the cursor position
      this.savedRange.deleteContents(); // Remove any selected text
      this.savedRange.insertNode(strongElement);

      // Create a space and an empty text node to reset formatting
      const space = document.createTextNode(" ");
      const normalTextNode = document.createTextNode("\u200B"); // Zero-width space to break formatting

      strongElement.after(space, normalTextNode);

      // Move the cursor after the normal text node
      this.savedRange.setStartAfter(normalTextNode);
      this.savedRange.setEndAfter(normalTextNode);

      // Update the selection
      selection.removeAllRanges();
      selection.addRange(this.savedRange);
    }
  }
}
  // Save cursor position
  saveCursorPosition(): void {
    const selection = window.getSelection();
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      this.savedRange = range.cloneRange(); // Clone the range to prevent modifications
    }
  }
  

  
  
  
// insertTextAtCursor(dyValue) {
//   console.log( this.sldDisplayDfd)
//   let dynamicText=""
//   const cursorPosition = this.getCursorPosition();
//    dynamicText = dyValue; // Replace this with your dynamic text

//   const spanElement = this.renderer.createElement('span');
//  // spanElement.className = "disableContent"
//    this.renderer.setAttribute(spanElement, 'contenteditable', 'false');
//   const textNode = this.renderer.createText(dynamicText);
//   this.renderer.appendChild(spanElement, textNode);

//   //const divElement = this.myDiv.nativeElement;
//   const divElement = document.getElementById('texteditor');
//   const childNodes = divElement.childNodes;

//   if (childNodes.length > 0) {
//     const previousNode = childNodes[cursorPosition - 1];
//     this.renderer.insertBefore(divElement, spanElement, previousNode);
//   } else {
//     this.renderer.appendChild(divElement, spanElement);
//   }
//   this.sldDisplayDfd=[]
// }
// /**
//    * @method function
//    * @name getCursorPosition(): number {
//    * @description get cursor position in the div element
// */
// getCursorPosition(): number {
//   const selection = window.getSelection();
//   if (selection.rangeCount > 0) {
//     const range = selection.getRangeAt(0);
//     const selectedNode = range.startContainer;
//     const cursorPosition = range.startOffset;

//     // If the selected node is a text node, find its position among its siblings
//     if (selectedNode.nodeType === Node.TEXT_NODE) {
//       let nodeIndex = 0;
//       let currentNode = selectedNode;

//       while ((currentNode = currentNode.previousSibling) !== null) {
//         nodeIndex++;
//       }

//       return nodeIndex + cursorPosition;
//     }
//   }

//   return 0; // Default to position 0 if no valid cursor position is found
// }

downloadAttachment(path: string, fileName: string): void {
  console.log("Original Path:", path);
  console.log("File Name:", fileName);

  // Check and replace base URL dynamically for localhost or stage
  let originalUrl = path;

  if (location.hostname === 'localhost') {
    originalUrl = path.replace('http://stage.minute.fit//', 'http://localhost:4200/api/');
  } else {
    originalUrl = path.replace('http://stage.minute.fit//', '');
  }

  console.log("Modified URL:", originalUrl);

  // Show progress dialog
  this.showDownloadDialog(fileName, "in-progress");

  // Make the HTTP request and download the file
  this.http.get(originalUrl, { responseType: 'blob' }).subscribe({
    next: (blob) => {
      saveAs(blob, fileName);
      console.log("Download complete for:", fileName);

      // Update dialog to show completion
      this.showDownloadDialog(fileName, "complete");
    },
    error: (error) => {
      console.error("Error downloading the file:", error);
      alert("Failed to download the file.");

      // Close dialog on error
      this.showDownloadDialog(fileName, "error");
    },
  });
}

// Function to display the download dialog
showDownloadDialog(fileName: string, status: string): void {
  const downloadDialog = document.querySelector("#downloadDialog");

  if (downloadDialog) {
    const dialogFileName = downloadDialog.querySelector("#dialogFileName");
    const dialogStatus = downloadDialog.querySelector("#dialogStatus");

    if (dialogFileName) dialogFileName.textContent = fileName;

    if (dialogStatus) {
      if (status === "in-progress") {
        dialogStatus.textContent = "Download in progress...";
      } else if (status === "complete") {
        dialogStatus.textContent = "Download complete!";
        setTimeout(() => downloadDialog.classList.remove("active"), 3000); // Auto close after 3 seconds
      } else if (status === "error") {
        dialogStatus.textContent = "Download failed!";
        setTimeout(() => downloadDialog.classList.remove("active"), 3000); // Auto close after 3 seconds
      }
    }

    downloadDialog.classList.add("active");
  }
}



closeDownloadModal(): void {
  this.isDownloadModalVisible = false;
}

isToday(date: string): boolean {
  const today = new Date();
  const givenDate = new Date(date);

  return (
    today.getFullYear() === givenDate.getFullYear() &&
    today.getMonth() === givenDate.getMonth() &&
    today.getDate() === givenDate.getDate()
  );
}



// End dynamic text field function
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
// prevent background color and font style for textarea


}



