import { Component, ElementRef, Renderer2, HostListener, OnInit, ViewChild } from '@angular/core';
import { ServicesService } from 'src/app/services.service';
// import * as AWS from 'aws-sdk/global';
// import * as Chime from 'aws-sdk/clients/chime';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

import {
  ConsoleLogger,
  DefaultMessagingSession,
  LogLevel,
  MessagingSessionConfiguration,

} from 'amazon-chime-sdk-js';
import { AuthserviceService } from 'src/app/authservice.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { Router } from '@angular/router';
import { ChattingService } from 'src/app/services/chatting/chatting.service';
import { isArray } from 'util';
@Component({
  selector: 'app-chatting',
  templateUrl: './chatting.component.html',
  styleUrls: ['./chatting.component.scss']
})
export class ChattingComponent implements OnInit {
  @ViewChild('scrollMe') private scrollMe: ElementRef;
  message = "";
  AllChannels = [];
  SelectedChannel = [];
  Placeholder = "Type here...";
  Messages = [];
  TempMessages = [];
  showReply: boolean = false;
  showQuestionReply: boolean = false;
  questionReply: any;
  replyMessage: any;
  replyUserName: any;
  replyUserAvatar: any;
  replyUserId = 0;
  replyMessageId = 0;
  @HostListener("document:click") hideOnClick() {
    this.showGIF = false;
  }
  replyMessageType: any;
  current_user: any;
  toggled: boolean = false;
  limitRecord: number = 0;
  SelectMessage = [];
  ChannelUsers = [];
  bkpChannelUsers = [];
  showHintUser: boolean = false;
  Replaytoggled: boolean = false;
  showGIF: boolean = false;
  isEdit: boolean = false;
  editMessageId: any;
  search: any;
  toggledView: boolean = false;
  replyEmoji = [
    {
      "char": "😀",
      "label": "grinning"
    },
    {
      "char": "😊",
      "label": "blush"
    },
    {
      "char": "🙂",
      "label": "slightly_smiling_face"
    },
    {
      "char": "😉",
      "label": "wink"
    },
    {
      "char": "😍",
      "label": "heart_eyes"
    },
    {
      "char": "😡",
      "label": "rage"
    },
    {
      "char": "😈",
      "label": "smiling_imp"
    },
    {
      "char": "👍",
      "label": "+1"
    },
    {
      "char": "🙏",
      "label": "pray"
    },
    {
      "char": "👌",
      "label": "ok_hand"
    },
    {
      "char": "🤝",
      "label": "handshake"
    },
    {
      "char": "✍️",
      "label": "writing_hand"
    },
    {
      "char": "👊",
      "label": "fist_oncoming"
    },
    {
      "char": "👋",
      "label": "wave"
    },
    {
      "char": "😲",
      "label": "astonished"
    }
  ]
  gifpopupopen = [
    {
      "id": 1,
      "type": "cute",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/cute10.gif"
    },
    {
      "id": 2,
      "type": "cute",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/cute5.gif"
    },
    {
      "id": 3,
      "type": "cute",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/cute7.gif"
    },
    {
      "id": 4,
      "type": "cute",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/cute8.gif"
    },
    {
      "id": 5,
      "type": "giphy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/giphy1.gif"
    },
    {
      "id": 6,
      "type": "giphy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/giphy2.gif"
    },
    {
      "id": 7,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy11.gif"
    },
    {
      "id": 8,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy12.gif"
    },
    {
      "id": 9,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy14.gif"
    },
    {
      "id": 10,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy15.gif"
    },
    {
      "id": 11,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy17.gif"
    },
    {
      "id": 12,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy18.gif"
    },
    {
      "id": 13,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy19.gif"
    },
    {
      "id": 14,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy2.gif"
    },
    {
      "id": 15,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy20.gif"
    },
    {
      "id": 16,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy4.gif"
    },
    {
      "id": 17,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy5.gif"
    },
    {
      "id": 18,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy6.gif"
    },
    {
      "id": 19,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy7.gif"
    },
    {
      "id": 20,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy8.gif"
    },
    {
      "id": 21,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy9.gif"
    },
    {
      "id": 22,
      "type": "love",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/love10.gif"
    },
    {
      "id": 23,
      "type": "love",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/love11.gif"
    },
    {
      "id": 24,
      "type": "love",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/love18.gif"
    },
    {
      "id": 25,
      "type": "love",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/love2.gif"
    },
    {
      "id": 26,
      "type": "party",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/party1.gif"
    },
    {
      "id": 27,
      "type": "party",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/party10.gif"
    },
    {
      "id": 28,
      "type": "party",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/party2.gif"
    },
    {
      "id": 29,
      "type": "party",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/party4.gif"
    },
    {
      "id": 30,
      "type": "party",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/party5.gif"
    },
    {
      "id": 31,
      "type": "sad",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/sad1.gif"
    },
    {
      "id": 32,
      "type": "sad",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/sad10.gif"
    },
    {
      "id": 33,
      "type": "sad",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/sad2.gif"
    },
    {
      "id": 34,
      "type": "sad",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/sad3.gif"
    },
    {
      "id": 35,
      "type": "sad",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/sad4.gif"
    },
    {
      "id": 36,
      "type": "sad",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/sad6.gif"
    },
    {
      "id": 37,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending11.gif"
    },
    {
      "id": 38,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending12.gif"
    },
    {
      "id": 39,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending13.gif"
    },
    {
      "id": 40,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending14.gif"
    },
    {
      "id": 41,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending16.gif"
    },
    {
      "id": 42,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending19.gif"
    },
    {
      "id": 43,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending2.gif"
    },
    {
      "id": 44,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending3.gif"
    },
    {
      "id": 45,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending6.gif"
    },
    {
      "id": 46,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending7.gif"
    },
    {
      "id": 47,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending9.gif"
    },
    {
      "id": 48,
      "type": "trending",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/trending11.gif"
    },
    {
      "id": 49,
      "type": "happy",
      "image": "https://chatgifs.s3.us-east-2.amazonaws.com/happy10.gif"
    }

  ]
  copyarray = []

  GifIcon = [
    {
      "type": "ALL",
      "name": "collections"
    },
    {
      "type": "Trending",
      "name": "trending_up"
    },
    {
      "type": "Happy",
      "name": "emoji_emotions"
    },
    {
      "type": "Love",
      "name": "favorite"
    },
    {
      "type": "Giphy",
      "name": "child_care"
    },
    {
      "type": "Cute",
      "name": "face_retouching_natural"
    },
    {
      "type": "Party",
      "name": "liquor"
    },

    {
      "type": "Sad",
      "name": "sentiment_dissatisfied"
    }
  ]
  /* Chime Variables Start */
  // chime = new Chime({ region: 'us-east-1' });
  showLargeImg: boolean = false;
  LargeImage: any;

  iframeUrl: SafeResourceUrl;
  authtoken = '';
  username: any;
  /* Chime Variables End */
  constructor(public service: ServicesService,
    public auth: AuthserviceService,
    public spinner: NgxSpinnerService,
    public router: Router,
    public chatService: ChattingService,
    private sanitizer: DomSanitizer,
    private renderer: Renderer2, 
    private elRef: ElementRef) {
    this.current_user = localStorage.getItem('CisspUserId');
    let userDetails = JSON.parse(localStorage.getItem('userdetails'));
    this.username = userDetails.name ;
    setTimeout(() => {
      this.service.headershow = true;
      this.service.SearchValue = true;
      this.service.headerset = {
        dashboard: false,
        studyguuide: false,
        knowledge: false,
        practice: false,
        cat: false,
        datestring: false,
        CATresult: false,
        CATQue: false,
        PracticeResult: false,
        Practiceques: false,
        studentprofile: false,
        knowques: false,
        knowresult: false,
        resource: false,
        liveSupport: false
      };
      var access = window.localStorage.getItem('accessitem');
      if (access) {
        var set = JSON.parse(<string>access);
        if (set) {
          this.service.access.CATaccess = set.CAT_access ? true : false;
          this.service.access.Knowaccess = set.KA_access ? true : false;
          this.service.access.Practiceaccess = set.PT_access ? true : false;
          this.service.access.livechat_access = set.livechat_access ? true : false;
        }
      }
    }, 100);
  }
  async ngOnInit() {
    await this.getAllChannel();
    this.copyarray = this.gifpopupopen;
    this.spinner.show();
    (await this.chatService.Rclogin(this.username, 'Newpassword02#')).subscribe(auth => {
      let data = JSON.parse(auth["_body"]).data;
      this.authtoken = data.authToken ;
      const userId = data.userId ;
      // this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(`http://localhost:3000/group/6660287f8b23d564bbcbe836?resumeToken=${this.authtoken}&layout=embedded`);
      // this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(`http://localhost:3000/group/Flexxon?resumeToken=${this.authtoken}&layout=embedded`);
      this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(`http://64.23.254.43:3100/group/Flexxon?resumeToken=${this.authtoken}&layout=embedded`);
    })
  }
  handleFileSelect(evt) {
    let me = this;
    let file = evt.target.files[0];
    let mime = "data:" + file.type + ";base64,";
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      me.uploadFile(reader.result, mime, file.type);
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };

  }
  async uploadFile(image, mime, file_type) {
    let fileType = file_type.toString().split("/")[1]
    this.spinner.show();
    var token = '';
    let file_upl = image.split("base64,")
    await this.chatService.uploadFile(file_upl[1], mime, fileType, token).then(async (imgresponse) => {
      if (imgresponse[0].status == 200) {
        var imglist = JSON.parse(<string>imgresponse[0].json);
        let user_id = localStorage.getItem('CisspUserId');
        let cohorts = this.AllChannels.filter(x => x.id == this.SelectedChannel['id']);
        let ref_number = this.generateRandom();
        let msg_type = ''
        if (fileType == 'png' || fileType == 'jpg' || fileType == 'jpeg' || fileType == 'gif') {
          msg_type = 'image'
        } else {
          msg_type = 'file'
        }
        await this.chatService.saveMessage(this.SelectedChannel['id'], user_id, msg_type, this.message, "", this.replyMessageId, this.replyUserId, this.replyUserName, this.replyUserAvatar, this.replyMessage, imglist.data, cohorts[0].userslist.toString(), ref_number, token).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.closeReply();
            this.sendChannelMessage();
            this.message = "";
          }
          this.spinner.hide();
        });
      }
      this.spinner.hide();
    });
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     let file_upl = image.split("base64,")
    //     await this.chatService.uploadFile(file_upl[1], mime, fileType, token).then(async (imgresponse) => {
    //       if (imgresponse[0].status == 200) {
    //         var imglist = JSON.parse(<string>imgresponse[0].json);
    //         let user_id = localStorage.getItem('CisspUserId');
    //         let cohorts = this.AllChannels.filter(x => x.id == this.SelectedChannel['id']);
    //         let ref_number = this.generateRandom();
    //         let msg_type = ''
    //         if (fileType == 'png' || fileType == 'jpg' || fileType == 'jpeg' || fileType == 'gif') {
    //           msg_type = 'image'
    //         } else {
    //           msg_type = 'file'
    //         }
    //         await this.chatService.saveMessage(this.SelectedChannel['id'], user_id, msg_type, this.message, "", this.replyMessageId, this.replyUserId, this.replyUserName, this.replyUserAvatar, this.replyMessage, imglist.data, cohorts[0].userslist.toString(), ref_number, token).then(async (data) => {
    //           if (data[0].status == 200) {
    //             var list = JSON.parse(<string>data[0].json);
    //             this.closeReply();
    //             this.sendChannelMessage();
    //             this.message = "";
    //           }
    //           this.spinner.hide();
    //         });
    //       }
    //       this.spinner.hide();
    //     });

    //   }
    // });

  }
  clickChannelUser(usr) {
    this.message += usr.aliasname ? usr.aliasname : usr.email;
    this.message += " ";
    this.showHintUser = false;
  }
  keyUpMessage(event) {
    if (event.keyCode == 50) {
      this.showHintUser = true;
    }
    let msg = "";
    if (this.message.startsWith("@")) {
      msg = this.message.substr(1, this.message.length);
    } else {
      this.showHintUser = false;
    }
    this.ChannelUsers = this.bkpChannelUsers.filter(function (str) {
      let email = "";
      email = str.aliasname ? str.aliasname : str.email;
      return email.toLowerCase().includes(msg.toLowerCase())
    });
  }
  clickReply(item) {
    this.showReply = true;
    this.replyMessageType = item.message_type;
    this.replyMessage = item.message_type == 'image' ? item.image : item.message;
    this.replyUserName = item.user.aliasname ? item.user.aliasname : item.user.email;
    this.replyUserAvatar = item.user.avatar_url;
    this.replyUserId = item.user.id;
    this.replyMessageId = item.id;
    var msgbox = document.getElementById("message") as HTMLInputElement;
    msgbox.focus();
  }
  closeReply() {
    this.showReply = false;
    this.replyMessage = "";
    this.replyUserName = "";
    this.replyUserAvatar = "";
    this.replyUserId = 0;
    this.replyMessageId = 0;
    this.SelectMessage = [];
    this.showGIF = false;
  }
  closeQuestionReply() {
    this.showQuestionReply = false;
    window.sessionStorage.removeItem("qdiscuss");
  }
  onPickedEmoji(event) {
    this.message += event.char;
  }
  messageSelection(i) {
    this.SelectMessage = [];
    this.SelectMessage[i] = true;
  }
  editMessage(item) {
    if (item.message.includes("<span class='my-email-chat'>")) {
      this.message = item.message.replace("<span class='my-email-chat'>", "")
      this.message = this.message.replace("</span>", "")
    } else {
      this.message = item.message;
    }
    this.isEdit = true;
    this.editMessageId = item.id;
  }
  async markAsRead(item) {
    let read_by = item.read_by;

    this.spinner.show();
    var token = '';
    await this.chatService.markAsRead(item.id, token).then(async (data) => {
    });
    this.spinner.hide();
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     await this.chatService.markAsRead(item.id, token).then(async (data) => {
    //     });
    //     this.spinner.hide();
    //   }
    // });
  }
  async deleteMessage(id) {
    this.spinner.show();
    var token = '';
    await this.chatService.deleteMessage(id, token).then(async (data) => {
      if (data[0].status == 200) {

        var index = this.Messages.map(x => {
          return x.id;
        }).indexOf(id);

        this.Messages.splice(index, 1);
        this.selectChannel(this.SelectedChannel)
      }
    });
    this.spinner.hide();
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     await this.chatService.deleteMessage(id, token).then(async (data) => {
    //       if (data[0].status == 200) {

    //         var index = this.Messages.map(x => {
    //           return x.id;
    //         }).indexOf(id);

    //         this.Messages.splice(index, 1);
    //         this.selectChannel(this.SelectedChannel)
    //       }
    //     });
    //     this.spinner.hide();
    //   }
    // });
  }
  showLargeImage(image) {
    this.showLargeImg = true;
    this.LargeImage = image
  }
  async getAllChannel() {
    this.spinner.show();
    var token = '';
    let user_id = localStorage.getItem('CisspUserId');
    await this.chatService.getAllChannel(user_id, token).then(async (data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        this.AllChannels = list.data;
        var certi_id = localStorage.getItem('CisspCourseId');
        let channel = this.AllChannels.filter(x => x.id == certi_id)
        this.selectChannel(channel[0]);
        let q = window.sessionStorage.getItem('qdiscuss');
        if (q) {
          this.showQuestionReply = true;
          this.questionReply = q;
          this.replyMessage = q;
          let userDetails = JSON.parse(localStorage.getItem('userdetails'));
          let uName = userDetails.aliasname ? userDetails.aliasname : userDetails.email;
          this.replyUserName = uName;
          this.replyUserId = parseInt(user_id);
          this.replyMessageId = 0;
        }
        else
          this.showQuestionReply = false;
      }
    });
    this.spinner.hide();
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     let user_id = localStorage.getItem('CisspUserId');
    //     await this.chatService.getAllChannel(user_id, token).then(async (data) => {
    //       if (data[0].status == 200) {
    //         var list = JSON.parse(<string>data[0].json);
    //         this.AllChannels = list.data;
    //         var certi_id = localStorage.getItem('CisspCourseId');
    //         let channel = this.AllChannels.filter(x => x.id == certi_id)
    //         this.selectChannel(channel[0]);
    //         let q = window.sessionStorage.getItem('qdiscuss');
    //         if (q) {
    //           this.showQuestionReply = true;
    //           this.questionReply = q;
    //           this.replyMessage = q;
    //           let userDetails = JSON.parse(localStorage.getItem('userdetails'));
    //           let uName = userDetails.aliasname ? userDetails.aliasname : userDetails.email;
    //           this.replyUserName = uName;
    //           this.replyUserId = parseInt(user_id);
    //           this.replyMessageId = 0;
    //         }
    //         else
    //           this.showQuestionReply = false;
    //       }
    //     });
    //     this.spinner.hide();
    //   }
    // });
    this.toggledView = true;
  }
  async selectChannel(item) {
    this.SelectedChannel = item;
    this.closeReply();
    this.showGIF = false;
    this.Replaytoggled = false;
    this.toggled = false;
    this.showReply = false;
    this.sendChannelMessage();
    this.Placeholder = "Write to " + item.certificate_name;
    this.limitRecord = 0;
    this.Messages = [];
    this.TempMessages = [];
    this.getMessage(item.id, this.limitRecord);
    if (item.userslist != "" && item.userslist != null) {
      this.spinner.show();
      var token = '';
      await this.chatService.getAllChannelUsers(item.userslist, token).then(async (data) => {
        if (data[0].status == 200) {
          var list = JSON.parse(<string>data[0].json);
          this.ChannelUsers = list.data;
          this.bkpChannelUsers = list.data;
        }
      });
      this.spinner.hide();
      // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      //   if (err) {
      //     await this.spinner.hide();
      //     this.router.navigate(['/login']);
      //   }
      //   else {
      //     var token = session
      //     await this.chatService.getAllChannelUsers(item.userslist, token).then(async (data) => {
      //       if (data[0].status == 200) {
      //         var list = JSON.parse(<string>data[0].json);
      //         this.ChannelUsers = list.data;
      //         this.bkpChannelUsers = list.data;
      //       }
      //     });
      //     this.spinner.hide();
      //   }
      // });
    }
    this.Replaytoggled = false;
    this.spinner.hide();
  }
  async sendMessage() {
    if (this.message && this.message.trim()) {
      let ref_number = this.generateRandom();
      if (this.isEdit) {
        var token = '';
        var data = {
          id: this.editMessageId,
          message: this.message
        };
        await this.chatService.emojiUpdate(data, token).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.isEdit = false;
            this.Messages.forEach(element => {
              if (element.id == this.editMessageId) {
                element.message = this.message;
              }
            });
            this.message = "";
          }
        });
        this.spinner.hide();
        // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        //   if (err) {
        //     await this.spinner.hide();
        //     this.router.navigate(['/login']);
        //   }
        //   else {
        //     var token = session
        //     var data = {
        //       id: this.editMessageId,
        //       message: this.message
        //     };
        //     await this.chatService.emojiUpdate(data, token).then(async (data) => {
        //       if (data[0].status == 200) {
        //         var list = JSON.parse(<string>data[0].json);
        //         this.isEdit = false;
        //         this.Messages.forEach(element => {
        //           if (element.id == this.editMessageId) {
        //             element.message = this.message;
        //           }
        //         });
        //         this.message = "";
        //       }
        //     });
        //     this.spinner.hide();
        //   }
        // });
      } else {
        let user_id = localStorage.getItem('CisspUserId');
        let userdetails = JSON.parse(localStorage.getItem('userdetails'));
        let msg = {
          channel_arn: "",
          cohort_id: localStorage.getItem('cohort_id'),
          createdAt: new Date().toISOString(),
          emoji_count: [],
          id: this.Messages.length > 0 ? (this.Messages[this.Messages.length - 1].id) + 1 : 1,
          image: "",
          message: this.message,
          message_id: "0",
          message_type: "text",
          mydate: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate(),
          read_by: "",
          reply_message: "",
          reply_user_avatar: "",
          reply_user_id: 0,
          reply_user_name: "",
          status: 0,
          updatedAt: new Date().toISOString(),
          user: {
            id: user_id,
            email: userdetails.email,
            name: userdetails.name,
            aliasname: userdetails.aliasname,
            avatar_url: userdetails.avatar_url
          },
          user_id: user_id,
          ref_number: ref_number
        }
        var x = [];
        x.push(msg)
        let already = this.Messages.filter(x => x.id == msg.id);
        if (already.length <= 0) {
          this.TempMessages.push(x);
          this.ChattingDetails(1);
        }
        x = [];
        let mmssgg = this.message;
        this.message = "";

        let cohorts = this.AllChannels.filter(x => x.id == this.SelectedChannel['id']);
        let noti = [];
        var token = '';
        await this.chatService.saveMessage(this.SelectedChannel['id'], user_id, "text", mmssgg, "", this.replyMessageId, this.replyUserId, this.replyUserName, this.replyUserAvatar, this.replyMessage, "", cohorts[0].userslist.toString(), ref_number, token).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.closeReply();
            let userDetails = JSON.parse(localStorage.getItem('userdetails'));
            let uName = userDetails.aliasname ? userDetails.aliasname : userDetails.email;
            this.bkpChannelUsers.forEach(element => {
              if (element.id != user_id) {
                noti.push({
                  user_id: element.id,
                  cohort_id: cohorts[0].id,
                  message: "New message from " + uName + " in " + cohorts[0].certificate_name + " channel",
                  noti_type: 'MESSAGE',
                  test_type: 'MESSAGE',
                  test_id: list.data.id,
                  is_read: 0,
                  fire_time: new Date().toISOString()
                })
              }
            });
            window.sessionStorage.removeItem("qdiscuss");
            this.showQuestionReply = false;
            await this.chatService.addNotification(noti, token);
            this.sendChannelMessage();
            this.message = "";
          }
        });
        this.spinner.hide();
        // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        //   if (err) {
        //     await this.spinner.hide();
        //     this.router.navigate(['/login']);
        //   }
        //   else {
        //     var token = session
        //     await this.chatService.saveMessage(this.SelectedChannel['id'], user_id, "text", mmssgg, "", this.replyMessageId, this.replyUserId, this.replyUserName, this.replyUserAvatar, this.replyMessage, "", cohorts[0].userslist.toString(), ref_number, token).then(async (data) => {
        //       if (data[0].status == 200) {
        //         var list = JSON.parse(<string>data[0].json);
        //         this.closeReply();
        //         let userDetails = JSON.parse(localStorage.getItem('userdetails'));
        //         let uName = userDetails.aliasname ? userDetails.aliasname : userDetails.email;
        //         this.bkpChannelUsers.forEach(element => {
        //           if (element.id != user_id) {
        //             noti.push({
        //               user_id: element.id,
        //               cohort_id: cohorts[0].id,
        //               message: "New message from " + uName + " in " + cohorts[0].certificate_name + " channel",
        //               noti_type: 'MESSAGE',
        //               test_type: 'MESSAGE',
        //               test_id: list.data.id,
        //               is_read: 0,
        //               fire_time: new Date().toISOString()
        //             })
        //           }
        //         });
        //         window.sessionStorage.removeItem("qdiscuss");
        //         this.showQuestionReply = false;
        //         await this.chatService.addNotification(noti, token);
        //         this.sendChannelMessage();
        //         this.message = "";
        //       }
        //     });
        //     this.spinner.hide();
        //   }
        // });
      }
    } else {
      this.service.ShowError("Type a messge to send")
    }
  }
  onScrollUp() {
    this.limitRecord += 10;
    this.getMessage(this.SelectedChannel['id'], this.limitRecord);
  }
  async getMessage(cohort_id, limitRecord = 0) {
    var token = '';
    await this.chatService.getMessage(cohort_id, limitRecord, token).then(async (data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        for (let i = 0; i < list.data.length; i++) {
          let already = this.Messages.filter(x => x.id == list.data[i].id);
          if (already.length <= 0) {
            var x = [];
            x.push(list.data[i])
            this.TempMessages.unshift(x);
            x = [];
          }
        }
        this.ChattingDetails();
      }
    });
    this.spinner.hide();
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     await this.chatService.getMessage(cohort_id, limitRecord, token).then(async (data) => {
    //       if (data[0].status == 200) {
    //         var list = JSON.parse(<string>data[0].json);
    //         for (let i = 0; i < list.data.length; i++) {
    //           let already = this.Messages.filter(x => x.id == list.data[i].id);
    //           if (already.length <= 0) {
    //             var x = [];
    //             x.push(list.data[i])
    //             this.TempMessages.unshift(x);
    //             x = [];
    //           }
    //         }
    //         this.ChattingDetails();
    //       }
    //     });
    //     this.spinner.hide();
    //   }
    // });
  }
  generateRandom() {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let ids = "";
    for (let id = 0; id < 16; id++) {
      ids += chars[Math.floor(Math.random() * chars.length)];
    }
    return ids;
  }
  async getSingleMessage(cohort_id) {
    var token = '';
    await this.chatService.getSingleMessage(cohort_id, token).then(async (data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        list.data = list.data.reverse()
        for (let i = 0; i < list.data.length; i++) {
          let already = this.Messages.filter(x => x.ref_number == list.data[i].ref_number);
          if (already.length <= 0) {
            var x = [];
            x.push(list.data[i])
            this.TempMessages.push(x);
            x = [];
            this.ChattingDetails(1);
          }
        }
      }
    });
    this.spinner.hide();
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     await this.chatService.getSingleMessage(cohort_id, token).then(async (data) => {
    //       if (data[0].status == 200) {
    //         var list = JSON.parse(<string>data[0].json);
    //         list.data = list.data.reverse()
    //         for (let i = 0; i < list.data.length; i++) {
    //           let already = this.Messages.filter(x => x.ref_number == list.data[i].ref_number);
    //           if (already.length <= 0) {
    //             var x = [];
    //             x.push(list.data[i])
    //             this.TempMessages.push(x);
    //             x = [];
    //             this.ChattingDetails(1);
    //           }
    //         }
    //       }
    //     });
    //     this.spinner.hide();
    //   }
    // });
  }
  groupByDate(array, key) {
    return array.reduce(function (rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }
  /* Chime Start */
  async sendChannelMessage() {
    const logger = new ConsoleLogger('SDK', LogLevel.OFF);
    let AppInstanceUserArn = "arn:aws:chime:us-east-1:462849534434:app-instance/f2c11c62-6879-4d3a-92bc-08cc3f3ded63/user/f2c11c62-6879-4d3a-92bc-08cc3f3ded63"
    const endpoint = "node001.ue1.ws-messaging.chime.aws";
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let ids = "";
    for (let id = 0; id < 20; id++) {
      ids += chars[Math.floor(Math.random() * chars.length)];
    }
    const sessionId = "1234657980";
    // const configuration = new MessagingSessionConfiguration(AppInstanceUserArn, sessionId, endpoint, this.chime, AWS);
    // const messagingSession = new DefaultMessagingSession(configuration, logger);

    const observer = {
      messagingSessionDidStart: () => {
      },
      messagingSessionDidStartConnecting: reconnecting => {
        if (reconnecting) {
        } else {
        }
      }, messagingSessionDidStop: event => {
      },
      messagingSessionDidReceiveMessage: message => {
        this.getSingleMessage(this.SelectedChannel['id']);
      }
    };

    // messagingSession.addObserver(observer);
    // messagingSession.start();
  }

  public ChattingDetails(isSingle = null) {
    let msg = [];
    for (const key in this.TempMessages) {
      this.TempMessages[key].forEach(element => {
        msg.push(element)
      });
    }
    this.Messages = msg;
    this.Messages.forEach(el => {
      el['mydate'] = el.createdAt.split("T")[0];
      if (el.emoji_count == null || el.emoji_count == undefined) {
        el.emoji_count = [];
      } else {
        if (!isArray(el.emoji_count)) {
          el.emoji_count = JSON.parse(el.emoji_count);
        }
      }
    });
    let grouping = [];
    let grouped = this.groupByDate(this.Messages, 'mydate');
    for (const key in grouped) {
      let date = new Date(key);
      let curr_date = new Date();
      curr_date.setDate(curr_date.getDate() - 1);
      let today = "";
      if (new Date(key).toISOString().split("T")[0] == new Date().toISOString().split("T")[0]) {
        today = "Today";
      } else if (date.toISOString().split("T")[0] == curr_date.toISOString().split("T")[0]) {
        today = "Yesterday";
      }
      let d = {
        createdAt: key,
        isdate: true,
        today: today
      }
      grouping.push(d);
      grouped[key].forEach(element => {
        if (element.message_type == 'text') {
          let m = element.message;
          if (!element.message.includes("<a href"))
            element.message = this.replaceURLs(element.message)
        }
        if (element.message_type == 'file') {
          let url = element.image
          let url_array = url.split("/")
          element['file_name'] = url_array[url_array.length - 1]
        }

        grouping.push(element)
      });
    }
    this.Messages = grouping;
    if (isSingle == 1) {
      setTimeout(() => {
        this.scrollMe.nativeElement.scrollTop = this.scrollMe.nativeElement.scrollHeight
      });
    } else {
      if (this.limitRecord < 10) {
        setTimeout(() => {
          this.scrollMe.nativeElement.scrollTop = this.scrollMe.nativeElement.scrollHeight
        });
      } else {
        setTimeout(() => {
          this.scrollMe.nativeElement.scrollTop = this.limitRecord * 50
        });
      }
    }
  }
  replaceURLs(message) {
    if (!message) return;
    var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
    return message.replace(urlRegex, function (url) {
      var hyperlink = url;
      if (!hyperlink.match('^https?:\/\/')) {
        hyperlink = 'http://' + hyperlink;
      }
      return '<a href="' + hyperlink + '" target="_blank" rel="noopener noreferrer" style="color: #7d56cc" class="mgs-link-color">' + url + '</a>'
    });
  }
  async onPickedrReplayEmoji(event, item) {
    this.Replaytoggled = false;
    var old_emoji = item.emoji_count ? item.emoji_count : [];
    if (old_emoji.length > 0) {
      var findEmoji = old_emoji.filter(x => x.label == event.label)
      if (findEmoji.length > 0) {
        old_emoji.forEach(element => {
          if (element.label == event.label) {
            element.count += 1;
          }
        });
      }
      else {
        old_emoji.push(
          {
            "label": event.label,
            "char": event.char,
            "count": 1
          }
        )
      }
    }
    else {
      old_emoji.push(
        {
          "label": event.label,
          "char": event.char,
          "count": 1
        }
      )
    }
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     var data = {
    //       id: item.id,
    //       emoji_count: JSON.stringify(old_emoji)
    //     };
    //     await this.chatService.emojiUpdate(data, token).then(async (data) => {
    //       if (data[0].status == 200) {
    //         var list = JSON.parse(<string>data[0].json);
    //       }
    //     });
    //     this.spinner.hide();
    //   }
    // });
    var token = '';
    var data = {
      id: item.id,
      emoji_count: JSON.stringify(old_emoji)
    };
    await this.chatService.emojiUpdate(data, token).then(async (data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
      }
    });
    this.spinner.hide();
  }
  async onPickederGifImage(GIF) {
    var token = '';
    let user_id = localStorage.getItem('CisspUserId');
    let cohorts = this.AllChannels.filter(x => x.id == this.SelectedChannel['id']);
    let ref_number = this.generateRandom();
    await this.chatService.saveMessage(this.SelectedChannel['id'], user_id, "image", this.message, "", this.replyMessageId, this.replyUserId, this.replyUserName, this.replyUserAvatar, this.replyMessage, GIF.image, cohorts[0].userslist.toString(), ref_number, token).then(async (data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        this.closeReply();
        this.sendChannelMessage();
        this.message = "";
      }
    });
    this.spinner.hide();
    // await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
    //   if (err) {
    //     await this.spinner.hide();
    //     this.router.navigate(['/login']);
    //   }
    //   else {
    //     var token = session
    //     let user_id = localStorage.getItem('CisspUserId');
    //     let cohorts = this.AllChannels.filter(x => x.id == this.SelectedChannel['id']);
    //     let ref_number = this.generateRandom();
    //     await this.chatService.saveMessage(this.SelectedChannel['id'], user_id, "image", this.message, "", this.replyMessageId, this.replyUserId, this.replyUserName, this.replyUserAvatar, this.replyMessage, GIF.image, cohorts[0].userslist.toString(), ref_number, token).then(async (data) => {
    //       if (data[0].status == 200) {
    //         var list = JSON.parse(<string>data[0].json);
    //         this.closeReply();
    //         this.sendChannelMessage();
    //         this.message = "";
    //       }
    //     });
    //     this.spinner.hide();
    //   }
    // });
  }
  Trendingfunc(itemname) {
    if (itemname.toLowerCase() == "all") {
      itemname = "";
    }
    this.gifpopupopen = this.copyarray.filter(item => { return item.type.toLowerCase().includes(itemname.toLowerCase()) })
  }
  searchfunc() {
    if (this.search.length != 0) {
      this.gifpopupopen = this.copyarray.filter(item => {
        return item.type.toLowerCase().includes(this.search.toLowerCase());
      })
    }
    else {
      return this.gifpopupopen = this.copyarray;
    }
  }
  showGifPopup(event) {
    event.stopPropagation();
    this.showGIF = !this.showGIF;
  }

  onIframeLoad(){
    this.spinner.hide();
    // const iframe = this.elRef.nativeElement.querySelector('#iframe') as HTMLIFrameElement;

    // if (iframe) {
    //   iframe.onload = () => {
    //     const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;

    //     if (iframeDoc) {
    //       // Wait for the DOM in the iframe to be fully loaded
    //       iframeDoc.addEventListener('DOMContentLoaded', () => {
    //         const boldButton = iframeDoc.querySelector('button[title="Bold"]');
    //         if (boldButton) {
    //           boldButton.remove(); // Remove the button from the DOM
    //         }
    //       });
    //     }
    //   };
    // }
  }
}