import moment from "moment";
import { Person, User, userRole } from "../models"
import { TreeNode } from "primeng/api";

type MyProName = "fatherId" | "motherId";

export class Utils {
   static toBase64 (file:any) 
   {
    let promise = new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    });
    return promise;
  }
    static getBase64(file: any) {
        let result: any;
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            result = reader.result;
            console.log('tobase64 ', result);
        };
        reader.onerror = function (error) {
            console.log('Error: ', error);
        };
    }
    static getCurrentUser(): User {

        let myUser = new User();
        myUser.username = "";
        const obj = sessionStorage.getItem('currentUser');
        //const obj = localStorage.getItem('currentUser');
        if (obj != undefined) {
            let user = JSON.parse(obj);
            myUser.firstName = user.firstName;
            myUser.id = user.id;
            myUser.lastName = user.lastName;
            myUser.role = user.role;
            myUser.username = user.username;
            myUser.email = user.email;
            myUser.token = user.token;
            myUser.phone = user.phone;
            myUser.department = user.department;
            myUser.position = user.position;
            myUser.managerEmail = user.managerEmail;



        }
        // console.log("[util] getcurrentUser",myUser);
        return myUser;
    }
    static setLocalStore(user: User): void {
        if (user && user.token) {
            // store user details and jwt token in local storage to keep user logged in between page refreshes
            // localStorage.setItem('currentUser', JSON.stringify(user));
            sessionStorage.setItem('currentUser', JSON.stringify(user));
        }
    }

    static getLastMonth(): Date {
        let result = moment().subtract(1, 'months').toDate();
        result.setDate(1);
        return result;
    }
    static getHome(): string {
        let result ="";
        const user = this.getCurrentUser();
        const urole = user.role;
        if (urole == userRole.Accounting)
        {
            result = "staffworkw";
        }
        else if (urole == userRole.Admin)
        {
            result = "staff";
        }
        else if (urole == userRole.ServiceManager)
        {
            result = "servicetask";
        }
        else if (urole == userRole.WorkShop)
        {
            result = "staffwork";
        }
        else if (urole == userRole.Normal)
        {
             result = "staff";
        }
        return result;
    }
    static getTimeStr(val:Date): string {
        let result = "00:00";
        if (val)
        {
            const hh = val.getHours();
            const min = val.getMinutes();
            if (hh < 10)
                result = '0' + hh.toString();
            else
                result = hh.toString();
            if (min < 10)
                result = result + ":0" + min.toString();
            else
                result = result + ":" + min.toString();

        }
        return result;
    }
     static canRunReport(role: number): boolean {
        let result = false;
        if (role == userRole.Admin)
            result = true;
        return result;
    }
static getUserRole(user: User): number {
        /*
        sysadmin
        request_manager
        ward_user
        */
        let ret = 0;
        if (user) {
            // console.log("utils user", user);
            if (user.role)
                ret = user.role;
        }
        return ret;
    }
    static getIsAuth(): boolean {
        const user = this.getCurrentUser();
        if (user.username != "") {
            return true;
        }
        else
            return false;
    }
    static getAdminRoleName(): number {
        return userRole.Admin;
    }
    static clearCurrentUser(): void {
        sessionStorage.clear();
        //localStorage.clear();
    }

static formatNode(item:Person): TreeNode
  {
    let label =  item.lastName + " " + item.firstName;
    let key = item.id.toString();
     let node: TreeNode ={
      key,
      label,
       type: 'person',
      data: {title: item.title, name: label, image: item.image},
      icon: 'pi pi-user'
     };

     return node;
  }
static getFileExtension(filename: string): string {
  const lastDotIndex = filename.lastIndexOf('.');
  if (lastDotIndex !== -1 && lastDotIndex < filename.length - 1) { // Ensure a dot exists and is not the last character
    return filename.substring(lastDotIndex + 1);
  }
  return ''; // No extension found
}
  static getChildForParentId(proName: MyProName , pid: number,childressNodes: Person[]): TreeNode[] {
    let result: TreeNode[] =[];
    let tree_node_child: TreeNode[];
    let node:TreeNode;
    let item: Person;
    
    const children = childressNodes.filter(x => x[proName] == pid);
    for (let c = 0; c < children.length; c++)
    {
          item = children[c];        
          node = this.formatNode(item);
          tree_node_child = this.getChildForParentId(proName,item.id, childressNodes);
          console.log("getChildForParentId childressNodes item tree_node_child ", childressNodes, item, tree_node_child);
          if (tree_node_child.length > 0)
          {
            node.expanded = true;
            node.children = tree_node_child;
          }
          result.push(node);
    }
    return result;
  }

static populateNode(proName: MyProName, familyList: Person[]): TreeNode[] {
        let familyTree: TreeNode[] = [];
        let node:TreeNode;
        let child_nodes:TreeNode[];
        
        let childressNodes:Person[];
       
        let item: Person;
        const topNodes = familyList.filter(x => x[proName]! < 1);
        childressNodes = familyList.filter(x => x[proName]! > 0);
        for(let i = 0; i < topNodes.length; i++)
        {
            item = topNodes[i];        
            node = Utils.formatNode(item);
            child_nodes = this.getChildForParentId(proName, item.id,childressNodes);
            console.log("populate getchildrenForParentId", child_nodes);
            if (child_nodes.length > 0)
            {
              node.expanded = true;
              node.children = child_nodes;
            }
            familyTree.push(node);
            //childressNodes = 
        }
        return familyTree;
      }
}