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

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

import { take } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { Router } from '@angular/router';
import { PersonService } from './person.service';
import { AuthenticationService } from '../user-services';
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 } from 'primeng/dynamicdialog';
import { PersonEdit } from './person.edit';
import { MessageService } from 'primeng/api';
import { CheckboxModule } from 'primeng/checkbox';
import { TreeModule, TreeNodeDoubleClickEvent, TreeNodeSelectEvent } from 'primeng/tree';
import { Utils } from '../shares';

@Component({
  selector: 'family-tree',
  templateUrl: './family.tree.html',
  imports:[TableModule,FormsModule,TreeModule,CheckboxModule, 
    OrganizationChartModule,CommonModule,
    FormsModule,
    ButtonModule,InputTextModule],
  styleUrls: ['./family.tree.css'],
  providers: [DialogService]
})
export class FamilyTree implements OnInit, OnDestroy{
  isFather = signal(true);
  private subscription:Subscription = new Subscription();
    firstname = '';
    selectedNode!: TreeNode;
    private cd = inject(ChangeDetectorRef);
    familyTree: TreeNode[] = [];
    email = '';
    lastname = '';
    _id = -10;
    loading = false;
    familyList:Person[] = [];
    msg ="[Person tree component]";
  private messageService = inject(MessageService);
  /*
  private store: Store<appValidationState>
  */
  constructor(  
    public dialogService: DialogService,
    private personService: PersonService,
    private authenticationService: AuthenticationService,
    private router: Router    
     ) {}
  getSearchCiteria(): StaffSearch {
    let criteria:StaffSearch = {
      email: this.email,
      firstName: this.firstname,
      lastName: this.lastname,
    };

    return criteria;

  }
  canSearch():boolean {
    let result = false;
    result = this.email !== "";
    result = result || this.lastname !== "";
    result = result || this.firstname !== "";
    return result;
  }
  ngOnInit(): void
  { 
    this.authenticationService.isHome = false;
    this.authenticationService.isReport = false;
  const prev = this.personService.searchCriteria;
    let goload = true;
    this.load();
    
  }  
  getActive(active:boolean):string {
    let result = 'false-icon pi-times-circle';
    if (active)
      result = 'true-icon pi-check-circle';
    return result;
  }
  load():void {
    let father = this.isFather(); 
      this.loading = true;
      //const criteria = this.getSearchCiteria();
      // this.personService.searchCriteria = criteria;
      this.subscription.add(
        this.personService.loadPersonFamilyTree(father, !father).subscribe(
          {
            next: x => {
              if (x.statusCode == 1)
              {
                this.familyTree = x.data;
                this.loading = false;
                this.cd.detectChanges();
                console.log("the family tree", this.familyTree);
              }
            },
            
      error: e => {      
      const message = e || e.message;
     // this.toastr.error(message);
     this.loading = false;
      console.log("error ", e);
      }
      }) 
    );   
  }
  
  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");
  }
  
  ngOnDestroy() {
		this.subscription.unsubscribe();
	}
}

