import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { PermissionNode } from "../utils/app.interfaces";
import { HttpURIService } from "../app.http.uri.service";
import { StorageService } from "../shared/services/storage.service";

@Injectable({
    providedIn: 'root'
})
export class ButtonManagementService {
    buttonPermissions: any = {};
    defaultPermission: any = {};

    constructor(private httpService: HttpURIService, private storageService: StorageService){
      this.defaultPermissions().subscribe((data: PermissionNode[]) => {
        this.defaultPermission = data;
        this.storageService.setItem("defaultPermission", JSON.stringify(data));
      });
    
    }

    traverse(nodes: any, isSuperAdmin: boolean) {
        if (!Array.isArray(nodes)) return;
    
        nodes.forEach(node => {
          // Check if the node has buttons
          if (node.buttons && Array.isArray(node.buttons) && node.buttons.length > 0) {
            // Create an object for this node's buttons
            this.buttonPermissions[node.name] = {};
            // Map each button's name to its checked value
            node.buttons.forEach((button:any) => {
              this.buttonPermissions[node.name][button.name] = isSuperAdmin? true : button.checked;
            });
          }
          // Recursively traverse children
          if (node.children && Array.isArray(node.children)) {
            this.traverse(node.children, isSuperAdmin);
          }
        });
    }

    setButtonPermissions(permission: any, isSuperAdmin: boolean){
      if (isSuperAdmin){
        if (Object.keys(this.defaultPermission).length === 0){
          this.defaultPermission = JSON.parse(this.storageService.getItem("defaultPermission") || '{}');
        }
        this.traverse(this.defaultPermission, isSuperAdmin);
      } else{
        this.traverse(permission, isSuperAdmin);
      }
    }

    defaultPermissions(): Observable<PermissionNode[]> {
          return this.httpService.requestGET<PermissionNode[]>('assets/data/sideMenu.json');
    }
}