import { Component, OnInit } from '@angular/core';
import { takeUntil } from 'rxjs';
import { Unsub } from '../../class/unsub.class';
import { AdminService } from '../../services/admin/admin.service';
import { GuestService } from '../../services/guest.service';
import { CookieService } from 'ngx-cookie-service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { LoaderService } from '../../services/loader.service';
import { TranslateService } from '@ngx-translate/core';
import { ActivatedRoute, NavigationStart, Router } from '@angular/router';

@Component({
  selector: 'app-customer-layout',
  templateUrl: './customer-layout.component.html',
  styleUrls: ['./customer-layout.component.scss'],
})
export class CustomerLayoutComponent extends Unsub implements OnInit {
  data;
  urlSegments;
  url;
  today = new Date();
  constructor(
    private adminService: AdminService,
    private guestService: GuestService,
    private translateservice: TranslateService, 
    private cookieService: CookieService, private sanitizer: DomSanitizer, loaderService: LoaderService,
    private router : Router
  ) {
     /**
     * This code calls the constructor of the parent class in a subclass. 
     * The super() function is used to initialize the parent class and allows access to its properties and methods. 
     * By calling  super(), the subclass can inherit and use the functionality of the parent class.
     **/
    super(loaderService);
    this.url = this.router.url;
    this.router.events.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (event: any) => {
        if (event instanceof NavigationStart) {
          this.url = event.url;
        }
      }
    })
    this.announcements();
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.announcements();
      }
    });
  }
  hideAlertsUntil: { [key: string]: number } = {};

  announcements() {
    this.guestService.getannouncments().subscribe({
      next: (res) => {
        this.data = res;
        if (res) {
          res.announcement?.forEach(alert => {
            const hideAlertsUntil = this.cookieService.get('anct' + alert.id);
            if (hideAlertsUntil) {
              this.hideAlertsUntil['anct' + alert.id] = parseInt(hideAlertsUntil, 10);
            }
          })
          res.announcements?.forEach(alert => {
            const hideAlertsUntil = this.cookieService.get('anct' + alert.id);
            if (hideAlertsUntil) {
              this.hideAlertsUntil['anct' + alert.id] = parseInt(hideAlertsUntil, 10);
            }
          })
        }
        if (res?.CUSTOMCHATENABLE == 'enable') {
          if (res?.CUSTOMCHATUSER == 'public') {
            if (document.querySelector('.customexternalchart')) {
              document.querySelectorAll('.customexternalchart').forEach(e => e.remove());
            }
            this.guestService.addExternalScript(res?.CUSTOMCHAT);
          } else if (res?.CUSTOMCHATUSER == 'user') {
            if (res?.customer) {
              if (document.querySelector('.customexternalchart')) {
                document.querySelectorAll('.customexternalchart').forEach(e => e.remove());
              }
              this.guestService.addExternalScript(res?.CUSTOMCHAT);
            }
          }
        } else {
          if (document.querySelector('.customexternalchart')) {
            document.querySelectorAll('.customexternalchart').forEach(e => e.remove());
          }
        }
      },
    });
  }

  hideAlertsUntils: { [key: string]: number } = {}
  dismissAlert(alert, type) {
    const hideAlertsUntil = (Date.now() + (30 * 60 * 1000)).toString();
    this.cookieService.set(type + alert.id, hideAlertsUntil, undefined, '/'); // Set cookie for 30 minutes from now
    this.hideAlertsUntils[type + alert.id] = parseInt(hideAlertsUntil, 10);
  }

  isAlertVisible(alert, type) {
    return !alert.dismissed && (!this.hideAlertsUntils?.[type + alert.id] || this.hideAlertsUntils?.[type + alert.id] < Date.now());
  }

  ngOnInit(): void {

    if (localStorage.getItem('lang') != null) {
      const data: any = localStorage.getItem('lang');
      this.translateservice.use(data);
    }

  }

  //For the Color change

  handleThemeUpdate(cssVars: any) {
    const root: any = document.querySelector(':root');
    const keys = Object.keys(cssVars);

    keys.forEach((key) => {
      root.style.setProperty(key, cssVars[key]);
    });
  }

  // to check the value is hexa or not
  isValidHex = (hexValue: any) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hexValue);

  getChunksFromString = (st: any, chunkSize: any) =>
    st.match(new RegExp(`.{${chunkSize}}`, 'g'));
  // convert hex value to 256
  convertHexUnitTo256 = (hexStr: any) =>
    parseInt(hexStr.repeat(2 / hexStr.length), 16);
  // get alpha value is equla to 1 if there was no value is asigned to alpha in function
  getAlphafloat = (a: any, alpha: any) => {
    if (typeof a !== 'undefined') {
      return a / 255;
    }
    if (typeof alpha != 'number' || alpha < 0 || alpha > 1) {
      return 1;
    }
    return alpha;
  };

  hexToRgba(hexValue: any, alpha = 1) {
    if (!this.isValidHex(hexValue)) {
      return null;
    }
    const chunkSize = Math.floor((hexValue.length - 1) / 3);
    const hexArr = this.getChunksFromString(hexValue.slice(1), chunkSize);
    const [r, g, b, a] = hexArr.map(this.convertHexUnitTo256);
    return `rgba(${r}, ${g}, ${b}, ${this.getAlphafloat(a, alpha)})`;
  }

  // convertion of hex code to rgba code

  dynamicLightPrimaryColor(color: any) {
    const cssPropName = `--primary`;

    this.handleThemeUpdate({
      [cssPropName]: this.hexToRgba(color),
    });
  }

  dynamicSecondaryColor(color: any) {
    const cssPropName = `--secondary`;

    this.handleThemeUpdate({
      [cssPropName]: this.hexToRgba(color),
    });
  }

  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
  // Function to add alpha channel to RGB color
  addAlphaChannel(rgbColor: string, alpha: number): string {
    // Extracting the RGB values
    const rgbValues = rgbColor.match(/\d+/g);
    if(rgbValues){
    // Constructing the RGBA color value
    const rgbaColor = `rgba(${rgbValues[0]}, ${rgbValues[1]}, ${rgbValues[2]}, ${alpha})`;
    return rgbaColor;
    }
    return rgbColor;
  }
}
