import { Component, OnInit, OnDestroy, inject, ChangeDetectorRef, signal} from '@angular/core';

import { StaffView ,StaffSearch, Person, RelationShip } from '../models';
import { OrganizationChartModule } from 'primeng/organizationchart';

import { take } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { PersonService } from './person.service';
import { TableModule } from 'primeng/table';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { ButtonModule } from 'primeng/button';
import { TreeNode } from 'primeng/api';
import { InputTextModule } from 'primeng/inputtext';
import { DialogService, DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';
import { PersonEdit } from './person.edit';
import { MessageService } from 'primeng/api';
import { TreeModule, TreeNodeDoubleClickEvent, TreeNodeSelectEvent } from 'primeng/tree';
import { Utils } from '../shares';

@Component({
  selector: 'family-orga',
  templateUrl: './family.orga.html',
  imports:[TableModule,FormsModule,TreeModule, OrganizationChartModule,CommonModule,ButtonModule,InputTextModule],
  styleUrls: ['./family.orga.css'],
  providers: [DialogService]
})
export class FamilyOrga implements OnInit, OnDestroy{

  private subscription:Subscription = new Subscription();
    person!: Person;
    selectedNode!: TreeNode;
    selectedNodes!: TreeNode[];
    private cd = inject(ChangeDetectorRef);
    familyTree = signal<TreeNode[]>([]);
    relations: RelationShip[] =[];
    _id = -10;
    loading = false;
    familyList:Person[] = [];
    msg ="[Person organise component]";
  private messageService = inject(MessageService);
  public ref = inject(DynamicDialogRef); 
  public config = inject(DynamicDialogConfig);
  /*
  private store: Store<appValidationState>
  */
 private personService = inject(PersonService);
 public dialogService = inject(DialogService);
  
  ngOnInit(): void
  { 
    const id = this.config.data.id;   
    this.familyList = this.config.data.familyList;
    const item = this.familyList.find(x => x.id == id);
    if (item != undefined)
      this.person = item;
    this.loadPersonFamilyTree(id);
   //this.populateTree();
    
  }  
  populateTree() : void {
    const data: TreeNode[] = [
        {
            expanded: true,
            type: 'person',
            styleClass: 'bg-indigo-500 text-white',
            data: {
                image: 'https://primefaces.org/cdn/primeng/images/demo/avatar/amyelsner.png',
                name: 'Amy Elsner',
                title: 'CEO'
            },
            children: [
                {
                    expanded: true,
                    type: 'person',
                    styleClass: 'bg-purple-500 text-white',
                    data: {
                        image: 'https://primefaces.org/cdn/primeng/images/demo/avatar/annafali.png',
                        name: 'Anna Fali',
                        title: 'CMO'
                    },
                    children: [
                        {
                            label: 'Sales',
                            styleClass: 'bg-purple-500 text-white',
                            style: ' border-radius: 12px'
                        },
                        {
                            label: 'Marketing',
                            styleClass: 'bg-purple-500 text-white',
                            style: ' border-radius: 12px'
                        }
                    ]
                },
                {
                    expanded: true,
                    type: 'person',
                    styleClass: 'bg-teal-500 text-white',
                    data: {
                        image: 'https://primefaces.org/cdn/primeng/images/demo/avatar/stephenshaw.png',
                        name: 'Stephen Shaw',
                        title: 'CTO'
                    },
                    children: [
                        {
                            label: 'Development',
                            styleClass: 'bg-teal-500 text-white'
                        },
                        {
                            label: 'UI/UX Design',
                            styleClass: 'bg-teal-500 text-white'
                        }
                    ]
                }
            ]
        }
    ];
    this.familyTree.set(data);
  }
  loadPersonFamilyTree(id: number): void {
  const relationShip$ = this.personService.loadPersonFamily(id);
    this.subscription.add(relationShip$.subscribe(
      {
        next: x => {
          if (x.statusCode == 1)
          {
            let tree : TreeNode[] =[];
            tree.push(x.data);
            this.familyTree.set(tree);
            console.log("load person family", this.familyTree());
           
          }
        },
        error: e => {
          console.error("error load loadPersonFamily by personId", id);
           this.messageService.add({severity:'error', summary: 'error load loadPersonFamily by personId', detail: e.message});
        }
      }
    ));
  }

  nodeSelect(event: TreeNodeSelectEvent) {
      //  this.messageService.add({ severity: 'info', summary: 'Node Selected', detail: event.node.label });
  }
nodeDoubleSelect(event:TreeNodeDoubleClickEvent) : void {
 // console.log("double click node", event.node.key);
  const id = event.node.key;
  this.edit(Number(id));
}

  getName(id:number): string
  {
    let result ="";
    const item = this.familyList.find(x => x.id == id);
    if (item)
      result = item.lastName + " " + item.firstName;
    return result;
  }
  updateParent(list:Person[]):void {
    let i = 0;
    let item:Person;
    for (i = 0; i< list.length; i++)
    {
      item = list[i];
      if (item.fatherId && item.fatherId > 0)
      {
        item.fatherName = this.getName(item.fatherId);
      }
    }
  }

  newFamily():void {
  //console.log("add new employee");
    this.personService.parentList = this.familyList;
  //  this.router.navigate( ['/family/new'], { queryParams: {returnUrl:'/family' } });
    this.showEdit(this._id--);
  }
  edit(id: number) : void {
    //console.log("edit family", id);
    this.personService.parentList = this.familyList;
   // this.router.navigate( ['/family/'+id], { queryParams: {returnUrl:'/family' } });
    this.showEdit(id);
  }
  showEdit(id:number) {
    const ref = this.dialogService.open(PersonEdit, {
      data: {
         id, 
         familyList: this.familyList,         
    },
      header: 'Family',
      width: '80%',
      maximizable: true
    });
    
    ref.onClose.subscribe((item: Person) => {
      if (item) {
        //console.log("after close ward edit", item);
        this.messageService.add({severity:'success', summary: 'Save Family', detail: item.firstName!});
       //update the current list
        this.updateList(item);
      }
      });

   }
   updateList(item: Person) :void {
    const idx = this.familyList.findIndex( x => x.id == item.id);
    if (item.fatherId && item.fatherId > 0)
      item.fatherName = this.getName(item.fatherId);
    if (item.motherId && item.motherId > 0)
      item.motherName = this.getName(item.motherId);
    if (idx < 0)
    {
      
      const olist = [... this.familyList, item];
      this.familyList = olist;
    }
    else
    {
      const oitem = this.familyList[idx];
      oitem.firstName = item.firstName;
      oitem.lastName = item.lastName;
      oitem.address = item.address;
      oitem.alive = item.alive;
      oitem.dob = item.dob;
      oitem.email = item.email;
      oitem.fatherId = item.fatherId;
      oitem.motherId = item.motherId;
      oitem.motherName = item.motherName;
      oitem.fatherName = item.fatherName;
      
    }
   }
  deleteItem(id: number): void {
    this.personService.deletePerson(id)
      .pipe(take(1))
      .subscribe({ next: result => {
      console.log(this.msg + " deleteItem success", result);
      
      const nlist = this.familyList.filter(d => d.id !== id);
      this.familyList = nlist;    
      },
      error: e => console.error(e)
    });
    //console.log(this.msg + "click button to delete");
  }
  close() :void {
     this.ref.close(null);
  }

  ngOnDestroy() {
		this.subscription.unsubscribe();
	}
}

