// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  IMPORTS
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

// Core Angular Imports
//----------------------------------------------------------

import { DatePipe } from "@angular/common";
import { 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
// 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
  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: string = "false";// checking Email is include or not while sending message
  isWhatsapp: string = "false";// checking whatsapp is include or not while sending message
  IsLSPlus: string = "false";// 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
// 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 
  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;
// Invoice Generate Details
  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=""
// 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
  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=[]// 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=[]// selected folder ID
  sldUsersGroupsList=[]// selected group list
  activeSendbtnList=[]// send btn active 
  viewInboxMsgdetails:boolean=false// inbox message menu is active or not
  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;
  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 = false;
 //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 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
  ) {




//  D.Data coming from service file (commquickview Components) 
// display selected User  in to Field
// -------------------------------------------------------
// ---------------------------------------------------------
     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);
    });

// ---------------------------------------------------------
// E. Data coming from service file (Template Components) 
// display selected template to compose and replay
// -------------------------------------------------------
    this._service._sendtemplate.subscribe((res) => {
      console.log(res);
      this.msgTemplateId=res.TemplateID
     if(res.TemplateID===1){

      if(res.subject!=""){
        this.isDynamicText=1
      }
      this.messageIndex=null
      this.messageTempID=null
       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;
     }

      else{
      this.messageIndex=null
      this.messageTempID=null
        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;
        const regex = /\{([^}]+)\}/g;
        console.log(this.bodytext)
        // this.bodytext.replace(regex, '<span class="highlight">$1</span>');
        // console.log(this.bodytext)
      }
     
    });

// ---------------------------------------------------------
// 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");
 

//---------------------------------------------------------

  });

// ---------------------------------------------------------
} // 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.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"));
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!=null){
  console.log("Hi sldUsersForUserCard Value")
  this.isComposeOpen = true;
  this.selectedMessageType("Compose");
  this.isMailcomingfromusercard=true
  this.receiverIDS.push(this.sldUsersForUserCard[0].XID);
  this.getAllInboxMessages();
  this.inboxmessageType = "List";
//  this._service.toggleViewCommunication(this.sldUsersForUserCard, "open","null");
  console.log(this.receiverIDS)
}
//-------------------------------------------------------------------------------
// Else Partis Normal Flow 
//-------------------------------------------------------------------------------
else{
  console.log("Hi Null Value")
  this.inboxmessageType = "List";
  this.selectedMessageType("List");
  this.getAllInboxMessages();
  this.receiverIDS=[]

  this.isMailcomingfromusercard=false
  //this._service.toggleViewCommunication(this.sldUsersForUserCard, "close","null");
  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()
//   }
// });

if(this.emailList.length==1 && this.messageType=="List"){
  console.log("this emailList length" ,this.emailList.length)
  //this.messageType=""
  this.isopendiv=false;
 this.isOpenrightsidebar=false;
}

 }    // End angular OnInt() method


// Angular AfterViewInit method 
// once load onint method after this method willn call  
//----------------------------------------------------- - -------------------------------------

  ngAfterViewInit() {
    console.log("Hi ngAfterViewInit Value")
    this.inboxmessageType = "List";
    
   if(this.sldUsersForUserCard==null){

   }
   this.getAllDraftMessages()
   this.getAllSentMessages();
   this.getFolderList()
   this.getDGFilters();

  } // 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();
    // }
    localStorage.removeItem("mailUserinfo");
    this.isMailcomingfromusercard=false
    this.sldUsersForUserCard=null
   
    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");
   
   
  }

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//  METHODS
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------
onFileChange(event: any) {
  const selectedFiles = event.target.files;
  for (let i = 0; i < selectedFiles.length; i++) {
    const file = selectedFiles[i];
    if (file.size <= 200 * 1024) { 
       // Check if the file size is less than 200KB

       const reader = new FileReader();
       reader.onload = (e: any) => {
         this.selectedFiles.push({
           file,
           url: e.target.result,
           filename: file.name,
           filetype: file.type
         });
       };
       reader.readAsDataURL(file);
      //this.files.push(file);
    } else {
      //alert(`${file.name} exceeds the 200KB size limit.`);
      this.notificationService.showNotification(file.name + "exceeds the 200KB size limit.");
    }
  }
  console.log(this.selectedFiles)
}

removeFile(index: number) {
  console.log(index)
  this.selectedFiles.splice(index, 1);
 // this.selectedFiles =  this.selectedFiles.filter(f => f.filename !== f.filename);
}



// downloadAttachment(url: string, fileName: string, index: number) {
//   console.log(url)
//   console.log(fileName)
//   console.log(index)

  
//   this.http.get(url, {
//     reportProgress: true,
//     observe: 'events',
//     responseType: 'blob' // To handle binary data
//   }).subscribe((event: HttpEvent<any>) => {
//     switch (event.type) {
//       case HttpEventType.DownloadProgress:
//         if (event.total) {
//           this.AttachmentPath[index].progress = Math.round(100 * event.loaded / event.total);
//         }
//         break;
//       case HttpEventType.Response:
//         saveAs(event.body, fileName);
//         this.AttachmentPath[index].progress = -1; // Reset progress
//         break;
//       default:
//         break;
//     }
//   }, error => {
//    // console.error('Download error:', error);
//     this.notificationService.showNotification('Download error:'+ error);
//     this.AttachmentPath[index].progress = -1; // Reset progress on error
//   });
// }




downloadAttachment(path: string, fileName: string): void {
  console.log(path)
  console.log(fileName)
  let originalUrl = path;
  //let modifiedUrl = originalUrl.replace('http://stage.minute.fit//', '/api/');
  //this._service.downloadFile(path, fileName);
  this.http.get(originalUrl, { responseType: 'blob' }).subscribe(blob => {
    saveAs(blob, fileName);
  });
  
  
}

/**
   * @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()
  }
  else if(value=="normal"){
    this.isThreadMode=false
  }
}
else if(this.messageType === 'Sent'){
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllSentMessages()
  }
  else if(value=="normal"){
    this.isThreadMode=false
    this.getAllSentMessages()
  }
}

else if(this.messageType === 'Draft'){
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllDraftMessages()
  }
  else if(value=="normal"){
    this.isThreadMode=false
   this.getAllDraftMessages()
  }
}
else if(this.messageType === 'Trash'){
  if(value=="thread"){
    this.isThreadMode=true
    this.getAllTrashMessages()
  }
  else if(value=="normal"){
    this.isThreadMode=false
   this.getAllTrashMessages()
  }
}

else if(this.messageType === 'FolderView'){
  if(value=="thread"){
    this.isThreadMode=true
   // this.getSelectedFolderMessages(this.allFolderList[0])
  // this.getSelectedFolderMessages(this.sentList)
  }
  else if(value=="normal"){
    this.isThreadMode=false
   // this.sentList=[]
  // this.getSelectedFolderMessages(this.allFolderList[0])
  }
}
  console.log(this.isThreadMode)
}









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()   
     };
   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("Messages are Added Sucessfully");
    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("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") {
       
     this.sldFolderMseageDetailsForDelete=[]
       this.getFolderList()
       this.refreshCard("Folder")
       //this.getSelectedFolderMessages(null)
       this.sldMsgIDS=[]
      this.closeDeleteFolderMessageWindow()
      this.notificationService.showNotification("Folder Messgae Deleted Sucessfully");
      // 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.models);
      this.updateNEWFolder()
  
    } else {
      console.log('Form is invalid');
    }
  
  
  }

 /**
   * @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
}
closeAddFolderWindow(){
 // this.foldername =""
  this.isModalOpenAddFolder=false
  this.isModalOpenUpdateFolder=false
 }
showUpdateFolderWindow(){

 this.isModalOpenUpdateFolder=true
}

openDeleteFolderMessageWindow(){
  this.isModalDeleteFolderMessage=true
}
closeDeleteFolderMessageWindow(){
  this.isModalDeleteFolderMessage=false
}

/**
  * @method Method
  * @name showCopyInboxMessageWindow
  * @description open Move inbox message to folder pop up window 
*/
showCopyInboxMessageWindow(){
      
this.isModalMoveFolderMessage=true
     
}

/**
   * @method Method
   * @name closeCopyInboxMessageWindow
   * @description moveinbox folder pop up window close
   * Refresh Card Inbox
*/
closeCopyInboxMessageWindow(){
  this.isModalMoveFolderMessage=false

}
/**
  * @method Method
  * @name showDeleteFolderWindow
  * @description delete  folder pop up window 
*/

showDeleteFolderWindow(){ 
  this.isModalOpenDeleteFolder=true
//  this.deleteSldFolder.show()
}

showDeleteTrashWindow(){

  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(){
   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.getFolderList()
       this.closeAddFolderWindow()
        this.notificationService.showNotification("Folder Updated Sucessfully");
        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("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(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--------------------------------------------------------------

  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.getFolderList()
       this.closeAddFolderWindow()
       this.foldername =""
        this.notificationService.showNotification("Folder Added Sucessfully");
  }
// Else
// Reset Form and show error message------------------------------------
  else{
      
      this.notificationService.showNotification("Somethings Went Wrong");

  }

    });
}

/**
   * @method Method
   * @name getFolderList
   * @description Get Folder List API  getmessagefolders
*/
getFolderList(){
 
  const url =this.notificationURL +"notifications/getmessagefolders/" +this.XBID +"/" +this.userID;

// API Call
//-----------------------------------------------------------------

  this.apiCall.makeGetApiCall(url).then((res: any) => {
    console.log(res)

//success stores folder List into array
//-----------------------------------------------------------------
   if(res.Status==="Success"){
     this.allFolderList=res.FolderDetails;
   
   }

// 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()

  });

}  

/**
   * @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 ----------------------------------------------------------

  const UserDeatils = {
    FolderID:this.sldFolderlist,
    XBID: this.XBID, 
    XID: this.userID,
    MessageIDs: this.sldMsgIDS.toString()   
  };

// 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")
        }
        this.sldFolderMseageDetailsForDelete=[]
        this.notificationService.showNotification("Messages are Added Sucessfully");
      }

// 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")
        }
        this.sldFolderlist=[]
        this.sldFolderMseageDetailsForDelete=[]
        this.notificationService.showNotification("Message Already Exist");
      }
   });

}

/** 
   * @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 Delete Folder Message its in selectd folder or in Every Where
   * Show the Modal while deleteing
   * and set value Selected or All
*/

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("Trash successfully emptied");
     this.messageType = ""
     this.messageType = "Trash"
     this.selectedEmail = null;
     this.refreshCard("Trash")
     this.getAllTrashMessages()
     this.closeDeleteTrashWindow()
   }
 });

}

/** 
   * @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.apiCall.makePostApiCall(url, UserDeatils).then((res: any) => {
    console.log(res);

// 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("Folder Deleted Sucessfully");
      this.getFolderList()
      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("Somethings Went Wrong");

    this.isActiveEdit=false;
    this.isActiveAdd=true;
    this.isActiveDeleteFolder=false
     }
  });

}

 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])
  }
    // this is used to take a specified line of messaage 
// 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);
  
});
  });
 }

 toggleThread(item,index: number): void {
  console.log(item)
  this.selectedThreadId = this.selectedThreadId === index ? null : index;
}



/**
   * @method Method
   * @name getAllInboxMessages
   * @description All Inbox Message
   * @GET API getAllMessages
*/
getAllInboxMessages() {
    this.emailList = [];
    this.selectedEmail=[]
    this.filteredEmailList=[]
// this.isComposeOpen=false;
//-----------------------------------------------------------
// API Call

  this.subscription = this._service .getAllMessages(this.userID,this.XBID).subscribe((res: any) => {
      console.log(res);
      this.sldInboxList=res
      this.sldInboxList.forEach(item => {
        item.displayTime  = this.formatDateOrTime(item.Date);
      });
      //this.sldInboxList=res
      console.log(res[res.length-1].TotalUnreadMessageCount)
      this.updateFilteredData()
// 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.emailList = []));

        if(this.isThreadMode==true){
          this.onSelectInbox(res[0])
        }

  });  

 
  
}

/**
   * ~ 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();
  }
}

/**
   * @method Method
   * @name updateFilteredData() {
   * @description Seach Inbox sent draft
*/
updateFilteredData() {
  console.log(this.sldInboxList)
 // if(this.inboxmessageType=='List'){
  this.filteredEmailList = this.sldInboxList.filter(item => 
    (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()))
  );
//}
// else{

// }
}

getPaginatedData() {
  const startIndex = (this.currentPage - 1) * this.itemsPerPage;
  return this.filteredEmailList.slice(startIndex, startIndex + this.itemsPerPage);
}

getPaginatedDataForList() {
  const startIndex = (this.currentPage - 1) * this.itemsPerPage;
  return this.filteredEmailList.slice(startIndex, startIndex + this.itemsPerPage);
}
onPageChange(page: number) {
  this.currentPage = page;
}

goToPreviousPage() {
  if (this.currentPage > 1) {
    this.currentPage--;
  }
}

goToNextPage() {
  if (this.currentPage < this.totalPages) {
    this.currentPage++;
  }
}

getDisplayedPages(): (number | string)[] {
  const pages: (number | string)[] = [];
  const maxDisplayedPages = 5; // Show at most 5 page numbers
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.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.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.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.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;
}
}

// nextPage() {
//   if ((this.currentPage * this.itemsPerPage) < this.filteredEmailList.length) {
//     this.currentPage++;
//   }
// }

// previousPage() {
//   if (this.currentPage > 1) {
//     this.currentPage--;
//   }
// }

onSearchChange() {
  this.currentPage = 1;
  this.updateFilteredData();
}

 /**
   * @method Method
   * @name getSelectedFolderMessages
   * @description Get All MEssages for Slected Folder using GET API getallmessagesinfolder
   */

 getSelectedFolderMessages(value){
  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
  console.log(value)
  this.emailList = [];
  this.sentList =[]
  this.sentList = value;
    this.sldInboxList=[]
    this.sentmessageid=[]
    this.activeSendbtnList=[]  
    this.filteredEmailList=[]
//--------------------------------------------------------------------------------
// API Called Here

const url = this.notificationURL + "notifications/getallmessagesinfolder/" + this.XBID + "/" + this.userID + "/" + this.selectedfolderid;
this.apiCall.makeGetApiCall(url).then((res: any) => {
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.updateFilteredData()
  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() {
    this.sentList = [];
    this.sldInboxList=[]
    this.sentmessageid=[]
    this.activeSendbtnList=[]
    this.filteredEmailList=[]
// Call GET API getAllSentMessages
//---------------------------------------------------------------------------------  

    this.subscription = this._service.getAllSentMessages(this.userID).subscribe((res: any) => {
    console.log(res);
    this.totalSentCount=res[res.length-1].TotalSentMessage

// Check the Response Length
//---------------------------------------------------------------------------------  
 if(res.length>=1){
       this.sentList = res;
       this.emailList = res
       this.sldInboxList=res
       this.sldInboxList.forEach(item => {
       
         item.displayTime  = this.formatDateOrTime(item.Date);
       });
       this.updateFilteredData()
       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(){
 
  this.emailList = [];
  this.selectedEmail=[]
  this.sentList = [];
  this.sldInboxList=[]
  this.sentmessageid=[]
  this.activeSendbtnList=[]
  this.filteredEmailList=[]
  //-----------------------------------------------------------
  // API Call

  this.subscription = this._service
    .getAllDraft(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.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.emailList = []));
      this.updateFilteredData()
// 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 getAllDraftMessages
   * @description Get All Draft Message Here
   * GET API getAllDraft with XID and BID
   */

getAllTrashMessages(){
 
  this.emailList = [];
  this.selectedEmail=[]
  this.sentList = [];
  this.sldInboxList=[]
  this.sentmessageid=[]
  this.activeSendbtnList=[]
  this.filteredEmailList=[]
  this.sldMsgIDS=[]
  //-----------------------------------------------------------
  // 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.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()
// Check Result Length is 1,make it empty
//-------------------------------------------------------------------        
    if(res.length==0){
      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
//-------------------------------------------------------------------  
    
      
    });

 
}

backToInboxList(){
  this.itemIsRead=false;
  this.inboxmessageType="List"
  this.isComposeOpen=false;
  this.selectedEmail=[]
  this.isThreadMode=false
 // this.selectedMessageType("List")
}

backToSentList(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'Sent'
  this.isThreadMode=false
  this.isComposeOpen=false;
}
backToDraftList(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'Draft'
  this.isThreadMode=false
  this.isComposeOpen=false;
}
backToTrashList(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'Trash'
  this.isThreadMode=false
  this.isTrashOpen=false;
}
backToFolderView(){
  this.itemIsRead=false;
  this.isSentSelected = false
  this.selectedEmail=[]
  this.messageType = 'FolderView'
  this.isThreadMode=false
  this.isTrashOpen=false;
}
//------------------------------------------------------------------------------------ 
/**
   * @method Method
   * @name onSelectInbox
   * @description Select Inbox Message
   * Inbox list messge selection and open View Window
*/

onSelectInbox(value){
  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.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)
      }
  }
  else{
    this.itemIsRead=true;
    this.selectedJ="" 
    let sentmessageids=[]
    this.selectedJ=value.MessageID
    console.log(this.messageType);
    console.log(this.isComposeOpen);
    this.isSentSelected=false
  // 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);
  //this.isOpenDraft=false
// ---------------------------------------------------------------------------------------------------  
// ---------------------------------------------------------------------------------------------------        
// If Sent means this Block it wil call   


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)
    }       
  }
      
  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)
    }
          
  }
      
  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"){
    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.draftID=value.MessageID;
   console.log(value)
 
   if(this.isThreadMode==false){
   this.isComposeOpen=true;
   //this.isOpenDraft=false
   }
   else{
    this.isComposeOpen=false;
    this.isOpenDraft=false
   }
// ---------------------------------------------------------------------------------------------------        
// 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
          }
            this.isDynamicGroup=true
            this.sldDynamicGroups.push(ids)
            }

          else{

            const ids={
              groupID:j.RecieverGroupID,
              groupName:j.RecieverGroupName
               
            }
  
            this.sldGroups.push(ids)
            }
            
          }
  }
      
}


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)
}
      
}
  
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(this.messageType === "FolderView"){
 
  this.inboxmessageType=""
  
  this.subjecttitle=value.Subject
  this.content=value.Message
  this.isSaveDraft=true;
  this.draftID=value.MessageID;
 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)
}
      
}
  
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 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;
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.messageType="Draft"),(this.getAllDraftMessages()))

      : value === "Trash"
      ? ((this.getPaginatedData()),(this.messageType="Trash"),(this.getAllTrashMessages()))

      : value === "Folder"
      ? ((this.getPaginatedData()),(this.messageType="Folder"),(this.getFolderList()),
      (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(foldeId); // Call getSelectedFolderMessages after 2 seconds
        } else {
          console.error('No folders available');
        }
      }, 1000))// 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
 
  var date=this.datePipe.transform(this.selectedEmail.Date, "yyyy-MM-dd")

  if(value.ThreadID!=null){
    this.ThreadID=value.ThreadID
  }
  else{
    this.ThreadID=null
  }
console.log(this.selectedEmail.RecieverXIDs);
console.log(this.selectedEmail);

let senderDetail

if(this.selectedEmail.RecieverXIDs.length!=0){
  this.receiverIDS=[]
for(let i of this.selectedEmail.RecieverXIDs){ 
console.log(i.RecieverFirstName)
  this.receiverIDS.push(i.RecieverXID); 

senderDetail = {
  XID: i.RecieverXID,
  firstName: i.RecieverFirstName,
  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=''))
: null;

}

else{

  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();
  
}


// -------------------------------------------------------------------------------------------------------------------
/**
   * ~ 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();
    }
}

//-----------------------------------------------------------------------------------------------------
/**
   * @updateReadMessage
   * @Get Inbox Message count
   * Method
   * Read Inbox Count API updatereadmessage
*/
updateReadMessage() {
    const url =
      this.notificationURL +
      "notifications/updatereadmessage/" +
      this.selectedEmail.MessageID +
      "/" +
      this.userID;
    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()
    });
}


//----------------------------------------------------------------------------------------------------------------------
//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);

  // 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(msg, event) {
//     console.log(this.messageType)
//     console.log(msg);
//     const checked = event.target.checked;
//     const deleteForFolderMessage={
//       MessageID:msg.MessageID,
//       Source:msg.Source,
//     }
// // Check and Stores Messge ID's    
// //------------------------------------------------------------------  

//   if (checked) {
//       this.sldMsgIDS.push(msg.MessageID);
//       this.sldFolderMseageDetailsForDelete.push(deleteForFolderMessage)
//   } 

// // UnCheck and remove Messge ID's    
// //------------------------------------------------------------------      
//   else {
//       const index = this.sldMsgIDS.findIndex((obj) => obj === msg.MessageID);
//       this.sldMsgIDS.splice(index, 1);

//       const index1 = this.sldFolderMseageDetailsForDelete.findIndex((obj) => obj.MessageID === msg.MessageID);
//       this.sldFolderMseageDetailsForDelete.splice(index1, 1);
//   }

// // Check the Length of array 
// //------------------------------------------------------------------  

//   this.sldMsgIDS.length > 0
//   ? ((this.isActiveDelete = true),(this.isActiveCopy=true))
//   : ((this.isActiveDelete = false),(this.isActiveCopy=false));
//   console.log(this.sldMsgIDS)
//   console.log(this.sldFolderMseageDetailsForDelete)
// }
onCheckMessage(item, event) {
  const checked = event.target.checked;

  // Update the checked property of the individual message
  item.checked = checked;

  // Handle adding/removing the message from selected items
  const deleteForFolderMessage = {
    MessageID: item.MessageID,
    Source: item.Source,
  };

  if (checked) {
    // Add to the selection arrays
    this.sldMsgIDS.push(item.MessageID);
    this.sldFolderMseageDetailsForDelete.push(deleteForFolderMessage);
  } else {
    // Remove from the selection arrays
    const index = this.sldMsgIDS.findIndex((id) => id === item.MessageID);
    if (index !== -1) this.sldMsgIDS.splice(index, 1);

    const index1 = this.sldFolderMseageDetailsForDelete.findIndex(
      (obj) => obj.MessageID === item.MessageID
    );
    if (index1 !== -1) this.sldFolderMseageDetailsForDelete.splice(index1, 1);
  }

  // Update the select-all checkbox state based on individual selections
  this.isAllSelected = this.getPaginatedDataForList().every((item) => item.checked);
}

/**
   * ~ onCheckMessage
     Select Message For Delete
   * # Method
   * @param(selected msg, event)
*/
onAllCheckMessage(event) {
  const checked = event.target.checked;

  // Update all items' checked status
  this.getPaginatedDataForList().forEach((item) => {
    item.checked = checked;
  });

  // Update the selection arrays
  if (checked) {
    this.sldMsgIDS = this.getPaginatedDataForList().map((item) => item.MessageID);
    this.sldFolderMseageDetailsForDelete = this.getPaginatedDataForList().map((item) => ({
      MessageID: item.MessageID,
      Source: item.Source,
    }));
  } else {
    this.sldMsgIDS = [];
    this.sldFolderMseageDetailsForDelete = [];
  }
}

// This method returns the paginated data for the list of messages
// getPaginatedDataForList() {
//   // Replace with your actual data fetching logic
//   return this.messages;
// }

deletewindowModel(){
  this.isModalOpenDelete=true
 }
 closewindowModel(){
   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("Message successfully deleted.");
        this.isActiveDelete = false;
        this.isActiveCopy=false
        this.messageType = ""
        this.messageType = "List"
        this.selectedEmail = null;
        this.getAllInboxMessages()
       this.closewindowModel()
        this.sldMsgIDS=[]
      
      }
    });
  
}

/**
   * ~ 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.isActiveDelete = false;
      this.isActiveCopy=false
      this.messageType = ""
      this.messageType = "Sent"
      this.selectedEmail = null;
      this.getAllSentMessages()
      this.closewindowModel()
    }
  });

}

//------------------------------------------------------
// 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.isActiveDelete = false;
      this.selectedEmail = null;
      this.isActiveCopy=false
     this.getAllDraftMessages()
     this.closewindowModel()
    
    }
  });

  }
  
}



//----------------------------------------------------------------------------------------------------------------------

/**
   * ~ openCommunicationQuickView
  @Send Data To QV From Card Conractor,Staff,Co-admin,Member
*/

openCommunicationQuickView(value,type){
console.log(value)
console.log(type)
console.log(this.sldUsers)
console.log(this.sldDynamicGroups)
console.log(this.sldUsersGroupsList)

//---------------------------------------------
// Default is Closed QV

//this.toggler.toggleQuickViewChat("Close");

   let sldUserGroup={
     customGroup:this.sldUsersGroupsList,
     dynamicGroup:this.sldDynamicGroups
  }
  
//---------------------------------------------
// 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)
  
   this._service.toggleViewCommunication(this.sldUsers, "open",this.sldUsersGroupsList);
   }

  }
  
}

//----------------------------------------------------------------------------------------------------------------------
/**
   * ~ 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() {
    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) {
   console.log(value)
   this.itemIsRead=false;
    this.selectedfolderid=""
    this.isDynamicGroup=false;
    this.isopendiv = false;
    this.isActiveCopy=false;
    this.isActiveDelete=false;
    this.sldUsers=[]
    this.receiverIDS=[]
    this.sldFolderID=null
    this.isActiveDeleteFolder=false;
    this.isActiveEdit=false;
    this.isActiveAdd=true;
    this.sldFolderMseageDetailsForDelete=[]
//------------------------------------------------------------------
// Type is List

  value === "List" 
  ? ((this.messageType = "List"),(this.inboxmessageType = 'List'),this.getAllInboxMessages(),
  (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.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.sldMsgIDS = []),
(this.isComposeOpen = false),
(this.selectedEmail = null),
(this.sldDGFilters = []), (this._service.toggleViewCommunication("value", "close","type")))
//------------------------------------------------------------------
// Else is Compose

  :((this.isComposeOpen = true),(this.getInboxMailCount()),
  (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.dearuser=""),(this.bodytext=""),(this.bestregards=""),(this.sign=""),
  (this.selectedEmail = null),(this.activeSendbtnList=[]),(this.sldDGFilters = []),
  console.log(this.isComposeOpen == true && this.isOpenDraft==false),
  (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");
}

//---------------------------------------------------------------------------------------------------------------------- 

/**
   * ~ 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

// 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.sldGroups)
    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:this.IsDraft,
      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("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("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("Draft Saved");
      //  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 = {
    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("Draft Saved");
//-------------------------------------------------------------------------------
      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("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 = "true";
    } else {
      this.isCheckInclude = "false";
    }
    console.log(this.isCheckInclude)
  }
//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ selectIncludeMail
   * * Check mail send notification to mail
   * # Method
   */
  selectIncludeMail(event) {
    const checked = event.target.checked;
    if (checked) {
      this.isWhatsapp = "true";
    } else {
      this.isWhatsapp = "false";
    }
    console.log(this.isWhatsapp)
  }

  selectIncludeLSPlus(event) {
    const checked = event.target.checked;
    if (checked) {
      this.IsLSPlus = "true";
    } else {
      this.IsLSPlus = "false";
    }
    console.log(this.isWhatsapp)
  }
//----------------------------------------------------------------------------------------------------------------------
  /**
   * ~ 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;
  this.bodyClass.add("slideprofile");
  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);
    
  }
  else{
    this.sldDFID=null
    const index1 = this.sldListDfd.findIndex(
      (pl) => pl.DFID == val.DFID
      );
      
    this.sldListDfd.splice(index1, 1);
   
  }
  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 text node with the dynamic field
      const textNode = document.createTextNode(dynamicField);

      // Insert the text node at the cursor position
      this.savedRange.insertNode(textNode);

      // Update the saved range to move the cursor after the inserted text
      this.savedRange.setStartAfter(textNode);
      this.savedRange.setEndAfter(textNode);

      // 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
    }
  }
}


  // Save cursor position
  saveCursorPosition(): void {
    const selection = window.getSelection();
    if (selection && selection.rangeCount > 0) {
      this.savedRange = selection.getRangeAt(0);
    }
  }
// 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
// }



// End dynamic text field function
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
}



