import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NbDialogService } from '@nebular/theme';
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
import { FamilyMember } from '../../entity/Member';
import { DomainType, PastoralDomain } from '../../entity/PastoralDomain';
import { BestListDlgComponent } from '../../happiness/best-list-dlg/best-list-dlg.component';
import { HappinessWeekListDlgComponent } from '../../happiness/happiness-week-list-dlg/happiness-week-list-dlg.component';
import { DomainMemberShipService } from '../../services/crudServices/domain-member-ship.service';
import { FamilyMemberService } from '../../services/crudServices/family-member.service';
import { PastoralDomainService } from '../../services/crudServices/pastoral-domain.service';
import { MsgBoxService } from '../../services/msg-box.service';
import { StateService } from '../../services/state.service';
import { FancySettings } from '../../ui/fancy-table/fancy-settings.model';
import { FancyTableComponent } from '../../ui/fancy-table/fancy-table.component';
import { ObjectUtils } from '../../utilities/object-utils';
import { PastoralDomainEditorComponent } from './pastoral-domain-editor/pastoral-domain-editor.component';

@Component({
  selector: 'ngx-pastoral-domains',
  templateUrl: './pastoral-domains.component.html',
  styleUrls: ['./pastoral-domains.component.scss']
})
export class PastoralDomainsComponent implements OnInit {

  @ViewChild(FancyTableComponent, { static: false }) fancyTable: FancyTableComponent<PastoralDomain>;
  data: PastoralDomain;
  allData: PastoralDomain[];
  selectedIndex: number = 0;
  isLoading: boolean = true;
  members: FamilyMember[];
  constructor(
    private pastoralDomainService: PastoralDomainService,
    private msgBoxService: MsgBoxService,
    private dlgService: NbDialogService,
    protected stateService: StateService,
    protected route: ActivatedRoute,
    private memberService: FamilyMemberService,
    private memberShipService: DomainMemberShipService

  ) {
  }

  //#region Table Setting
  settings = <FancySettings<PastoralDomain>>{
    contextMenuItems: [
      {
        id: 'add',
        enabled: true,
        title: 'Add New',
        icon: 'plus-circle-outline',
        callback: (datum, element) => {
          this.openEditingDialog(true);
        },
      },
      {
        id: 'edit',
        enabled: true,
        title: 'Edit',
        icon: 'edit',
        callback: (datum, element) => {
          this.openEditingDialog(false);
        },
      },
      {
        enabled: true,
        id: 'delete',
        title: 'Delete',
        icon: 'trash-2-outline',
        callback: (datum, element) => {
          this.delete(datum);
        },
      },
      {
        enabled: true,
        id: 'happinessBest',
        title: 'Bests',
        icon: 'smiling-face-outline',
        callback: (datum, element) => {
          this.openBestListDlg(datum);
        },
      },
      {
        enabled: true,
        id: 'happinessWeek',
        title: 'Week Info',
        icon: 'smiling-face-outline',
        callback: (datum, element) => {
          this.openHappinessWeekListDlg(datum);
        },
      },
      {
        enabled: true,
        id: 'members',
        title: 'Members',
        icon: 'people-outline',
        callback: (datum, element) => {
          this.openMemberAssignDlg(datum);
        },
      }
    ],
    onContextMenuOpening: (datum, menuItems) => {
      menuItems.find(i => i.id == 'delete').visible = !!datum;
      menuItems.find(i => i.id == 'edit').visible = !!datum;
      menuItems.find(i => i.id == 'happinessBest').visible = datum.type == DomainType.HappinessGroup;
      menuItems.find(i => i.id == 'happinessWeek').visible = datum.type == DomainType.HappinessGroup;
      //menuItems.find(i => i.id == 'members').visible = datum.type == DomainType.HappinessGroup;
      return datum;
    },
    columns: [
      {
        name: 'type',
        title: 'Type',
        type: 'number',
        group: true,
        visible: false,
        groupValuePrepareFunction: (v) => this.getDomainTypeName(v.type)
      },
      {
        name: 'name',
        title: 'Name',
        type: 'text',
        widthPx: 150,
        //valuePrepareFunction: (item) => ,
      },
      {
        name: 'description',
        title: 'Description',
        type: 'text',
        widthPct: 70,
        //valuePrepareFunction: (item) => ,
      },
      {
        name: 'leaderMemberId',
        title: 'Leader',
        type: 'text',
        widthPx: 150,
        valuePrepareFunction: (item) => {
          return this.displayLeaderInfo(item.leaderMemberId)
        }
      },
      // {
      //   name: 'image1',
      //   title: 'Image1',
      //   type: 'text',
      //   widthPx: 100,
      //   //valuePrepareFunction: (item) => ,
      // },
      // {
      //   name: 'members',
      //   title: 'Members',
      //   type: 'text',
      //   widthPx: 100,
      //   //valuePrepareFunction: (item) => ,
      // },

    ],
  };
  //#endregion

  //#region Implements Methods

  ngOnInit(): void {
    this.memberService.getAll().pipe(first()).subscribe(result => {
      this.members = result;
      this.getAllData();
    });
  }

  get saveMethod(): Observable<any> {
    return Observable.of(true);
  }
  getAllData() {
    this.isLoading = true;
    this.pastoralDomainService.getAll().pipe(first()).subscribe(result => {
      this.isLoading = false;
      this.allData = result;
    });
  }
  //#endregion

  //#region UI Calling Methods
  openEditingDialog(isAdding: boolean) {
    this.dlgService.open(PastoralDomainEditorComponent, {
      context: {
        data: isAdding ? null : ObjectUtils.CloneValue(this.allData[this.selectedIndex]),
        isAdding: isAdding,
        members: this.members
      }
    }).onClose.pipe(first()).subscribe(result => {
      if (result) {
        this.getAllData();
      }
    });
  }

  //#endregion

  //#region CRUD Methods
  delete(datum) {
    this.msgBoxService.showConfirmDeleteBox().pipe(first()).subscribe(answer => {
      if (answer === true) {
        this.isLoading = true;
        this.pastoralDomainService.delete(datum).pipe(first()).subscribe(result => {
          this.isLoading = false;
          this.allData.splice(this.selectedIndex, 1);
          this.fancyTable.reload();
        });
      }
    });
  }
  //#endregion

  private displayLeaderInfo(id: string) {
    var member = this.members.find(m => m.id == id);
    if (member) {
      return `${member.firstName} ${member.lastName}`;
    }
    return 'N/A';
  }

  private openHappinessWeekListDlg(datum: PastoralDomain) {

    this.dlgService.open(HappinessWeekListDlgComponent, {
      context: {
        group: datum
      }
    }).onClose.pipe(first()).subscribe(result => {
      this.getAllData();
    });
  }
  private openBestListDlg(datum: PastoralDomain) {

    this.dlgService.open(BestListDlgComponent, {
      context: {
        group: datum
      }
    }).onClose.pipe(first()).subscribe(result => {
      this.getAllData();
    });
  }

  private getDomainTypeName(type: DomainType): string {
    switch (type) {
      case DomainType.CellGroup: return "細胞小組";
      case DomainType.HappinessGroup: return "幸福小組";
      case DomainType.CellGroupCoworker: return "細胞同工";
      case DomainType.ChurchCoworker: return "教會事工";
      case DomainType.Administrator: return "管理員";
      default: break;
    }
  }

  private openMemberAssignDlg(datum: PastoralDomain) {

    // this.msgBoxService.showListBox<FamilyMember>(
    //   `Members in ${datum.name}`,
    //   this.members,
    //   'id',
    //   datum.familyMembers.map(m => m.id),
    //   (e) => `${e.firstName} ${e.lastName} (${e.email})`
    // ).pipe(first()).subscribe(result => {
    //   if (result) {

    //     datum.familyMembers = result;
    //     this.memberShipService.updateMembersInGroup(datum).pipe(first()).subscribe(result => {

    //     });
    //   }
    // });
  }
}
