import { Component, OnInit } from '@angular/core';
import { Events, MenuController, ModalController } from '@ionic/angular';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { AuthenticatedUser } from 'src/app/hmg-common/services/authentication/models/authenticated-user';
import { PerformanceAppraisalResponse } from 'src/app/hmg-common/services/dashbored/performance-appraisal.response';
import { DashboredService } from 'src/app/hmg-common/services/dashbored/dashbored.service';
import { SharedDataService } from 'src/app/hmg-common/services/shared-data-service/shared-data.service';
import { DomSanitizer } from '@angular/platform-browser';
import { EditDetailProfileComponent } from '../modal/edit-detail-profile/edit-detail-profile.component';
import { ProfileService } from '../service/profile.service'
import { ActivatedRoute } from '@angular/router';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  public direction: string;
  public setImage: any;
  public user_image: any = '../assets/imgs/profile.png';
  public personalInfo: any;
  public appraisalArr: any = [];
  public performanceData: any = [];
  public static PERFORMANCE_DATA = 'perAppData';
  public personalInfoSegment = false;
  public basicDetailsSegment = false;
  public addressSegment = false;
  public editBasic = false;
  public editAddress = false;
  public targetValue: any;
  public employeeBasicDetails: any = [];
  public fullName: string;
  public maritalStatus: string;
  public birthDate: any;
  public civilIdentityNumber: any;
  public menuEntries: any;
  public basicDetailsSubMenu: any;
  public addressSubMenu: any;
  public transactionNo = 0;
  public address: any;
  public street: any;
  public area: any;
  public poBox: any;
  public city: any;
  public postalCode: any;
  public country: any;
  public employeeAdress: any = [];
  public jobName: any;

  constructor(
    public ts: TranslatorService,
    public cs: CommonService,
    public authService: AuthenticationService,
    public DS: DashboredService,
    public sharedData: SharedDataService,
    public events: Events,
    private sanitizer: DomSanitizer,
    public modalController: ModalController,
    public profileService: ProfileService,
    public router: ActivatedRoute
  ) {
    this.direction = TranslatorService.getCurrentDirection();
    this.events.subscribe('img-change', displayImg => {
      console.log('app compont: ' + displayImg);
      this.user_image = this.sanitizer.bypassSecurityTrustUrl('data:Image/*;base64,' + displayImg);
    });
    this.router.queryParams.subscribe(params => {
      this.targetValue = params.targetValue;
      if (this.targetValue === 'sideMenu') {
        this.personalInfoSegment = true;
        this.basicDetailsSegment = false;
        this.addressSegment = false;
      } else if (this.targetValue === 'basicDetails') {
        this.personalInfoSegment = false;
        this.basicDetailsSegment = true;
        this.addressSegment = false;
      } else if (this.targetValue === 'address') {
        this.personalInfoSegment = false;
        this.basicDetailsSegment = false;
        this.addressSegment = true;
      } else {
        this.personalInfoSegment = true;
        this.basicDetailsSegment = false;
        this.addressSegment = false;
      }
    });
  }

  ngOnInit() {
    this.getProfile();
    this.menuEntries = this.cs.sharedService.getSharedData('menuEntries', false);
    if (this.menuEntries) {
      this.setMenuEntries();
    }
  }

  public setMenuEntries() {
    let personalInformationChildren: any;
    let personalInfoNestedChildren: any;

    if (this.targetValue === 'sideMenu') {
      for (let i = 0; i < this.menuEntries.length; i++) {
        if (this.menuEntries[i].MENU_NAME === 'MBL_E_PROFESSIONALS_01') {
          personalInformationChildren = this.menuEntries[i].children;
          for (let j = 0; j < personalInformationChildren.length; j++) {
            if (personalInformationChildren[j].MENU_NAME = 'MBL_PERINFO_SS' && personalInformationChildren[j].ENTRY_SEQUENCE === 15) {
              personalInfoNestedChildren = personalInformationChildren[j].children;
              for (let k = 0; k < personalInfoNestedChildren.length; k++) {
                if (personalInfoNestedChildren[k].REQUEST_TYPE === 'BASIC_DETAILS') {
                  this.basicDetailsSubMenu = personalInfoNestedChildren[k];
                }
                if (personalInfoNestedChildren[k].REQUEST_TYPE === 'ADDRESS') {
                  this.addressSubMenu = personalInfoNestedChildren[k];
                }
              }
            }
          }
        }
      }
    } else {
      const menuEntriesLocalArray: any = this.menuEntries.children;
      for (let i = 0; i < menuEntriesLocalArray.length; i++) {
        if (menuEntriesLocalArray[i].REQUEST_TYPE === 'BASIC_DETAILS') {
          this.basicDetailsSubMenu = menuEntriesLocalArray[i];
        }
        if (menuEntriesLocalArray[i].REQUEST_TYPE === 'ADDRESS') {
          this.addressSubMenu = menuEntriesLocalArray[i];
        }
      }
    }
    console.log(this.basicDetailsSubMenu);
    console.log(this.addressSubMenu);
  }

  public getProfile() {
    console.log('getProfile');
    this.authService
      .loadAuthenticatedUser()
      .subscribe((user: AuthenticatedUser) => {
        if (user) {
          console.log(user);
          this.personalInfo = user;

          let jobTitle = user.POSITION_NAME.split('.');
          if (jobTitle && jobTitle.length > 1) {
            this.jobName = jobTitle[0] + " " + jobTitle[1];
          }​

          if (this.cs.getUpdateImage().status) {
            this.user_image = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,' + this.cs.getUpdateImage().img);
          } else {
            this.user_image = user.EMPLOYEE_IMAGE
              ? 'data:image/png;base64,' + user.EMPLOYEE_IMAGE
              : '../assets/imgs/profile.png';
          }
          this.getBasicDetails();
          this.getAddress();
        }
      });
  }

  public getBasicDetails() {
    const body = {
      P_SELECTED_EMPLOYEE_NUMBER: this.personalInfo.EMPLOYEE_NUMBER,
      P_MENU_TYPE: "E",
      P_SELECTED_RESP_ID: -999
    };
    this.profileService.getEmployeeBasicDetails(body).subscribe((result: any) => {
      if (this.cs.validResponse(result)) {
        this.employeeBasicDetails = result.GetEmployeeBasicDetailsList;
        this.cs.sharedService.setSharedData(this.employeeBasicDetails, 'employeeDetails');
        console.log(this.employeeBasicDetails);
        for (let i = 0; i < this.employeeBasicDetails.length; i++) {
          if (this.employeeBasicDetails[i].APPLICATION_COLUMN_NAME === 'FULL_NAME') {
            this.fullName = this.employeeBasicDetails[i].SEGMENT_VALUE_DSP;
          } else if (this.employeeBasicDetails[i].APPLICATION_COLUMN_NAME === 'MARITAL_STATUS') {
            this.maritalStatus = this.employeeBasicDetails[i].SEGMENT_VALUE_DSP;
          } else if (this.employeeBasicDetails[i].APPLICATION_COLUMN_NAME === 'DATE_OF_BIRTH') {
            this.birthDate = this.employeeBasicDetails[i].SEGMENT_VALUE_DSP;
          } else if (this.employeeBasicDetails[i].APPLICATION_COLUMN_NAME === 'NATIONAL_IDENTIFIER') {
            this.civilIdentityNumber = this.employeeBasicDetails[i].SEGMENT_VALUE_DSP;
          }
        }
      }
    });
  }

  public getAddress() {
    const body = {
      P_SELECTED_EMPLOYEE_NUMBER: this.personalInfo.EMPLOYEE_NUMBER,
      P_MENU_TYPE: "E",
      P_SELECTED_RESP_ID: -999
    };
    this.profileService.getEmployeeAddress(body).subscribe((result) => {
      console.log(result);
      this.employeeAdress = result.GetEmployeeAddressList;
      this.country = { name: result.P_COUNTRY_NAME, code: result.P_COUNTRY_CODE }
      for (let i = 0; i < this.employeeAdress.length; i++) {
        if (this.employeeAdress[i].APPLICATION_COLUMN_NAME === 'ADDRESS_LINE1') {
          this.address = this.employeeAdress[i].SEGMENT_VALUE_DSP;
        } else if (this.employeeAdress[i].APPLICATION_COLUMN_NAME === 'REGION_1') {
          this.street = this.employeeAdress[i].SEGMENT_VALUE_DSP;
        } else if (this.employeeAdress[i].APPLICATION_COLUMN_NAME === 'REGION_2') {
          this.area = this.employeeAdress[i].SEGMENT_VALUE_DSP;
        } else if (this.employeeAdress[i].APPLICATION_COLUMN_NAME === 'REGION_3') {
          this.poBox = this.employeeAdress[i].SEGMENT_VALUE_DSP;
        } else if (this.employeeAdress[i].APPLICATION_COLUMN_NAME === 'TOWN_OR_CITY') {
          this.city = this.employeeAdress[i].SEGMENT_VALUE_DSP;
        } else if (this.employeeAdress[i].APPLICATION_COLUMN_NAME === 'POSTAL_CODE') {
          this.postalCode = this.employeeAdress[i].SEGMENT_VALUE_DSP;
        }
      }
    })
  }

  public openEditprofile() {
    this.cs.openProfile('sideMenu');
  }

  public openPerormance() {
    this.showPerformanceAppraisal();
  }

  public showPerformanceAppraisal() {
    this.DS.getPerformanceAppraisal(() => {
      this.showPerformanceAppraisal();
    }).subscribe((result: PerformanceAppraisalResponse) => {
      this.handlePerformanceAppraisalResult(result);
    });
  }

  private handlePerformanceAppraisalResult(result) {
    if (this.cs.validResponse(result)) {
      if (this.cs.hasData(result.GetPerformanceAppraisalList)) {
        this.appraisalArr = result.GetPerformanceAppraisalList;
        this.performanceData = [];
        for (let i = 0; i < this.appraisalArr.length; i++) {
          this.performanceData.push({ name: this.appraisalArr[i].APPRAISAL_YEAR, value: parseInt(this.appraisalArr[i].APPRAISAL_SCORE).toFixed() });
        }
        console.log('PerformanceAppraisalResponse');
        this.sharedData.setSharedData(this.performanceData, PerformanceAppraisalResponse.PERFORMANCE_DATA);
        this.cs.openPerformanceevaluation();
      } else {
        let msg: string = this.ts.trPK("userProfile", "no-appraisal");
        this.cs.presentAlert(msg);
      }
    }
  }

  public selectedSegment(segmentData) {
    switch (segmentData) {
      case "personal":
        this.personalInfoSegment = true;
        this.basicDetailsSegment = false;
        this.addressSegment = false;
        this.editBasic = false;
        this.editAddress = false;
        break;
      case "basic":
        this.personalInfoSegment = false;
        this.basicDetailsSegment = true;
        this.addressSegment = false;
        this.editBasic = false;
        this.editAddress = false;
        break;
      case "address":
        this.personalInfoSegment = false;
        this.basicDetailsSegment = false;
        this.addressSegment = true;
        this.editBasic = false;
        this.editAddress = false;
        break;
    }
  }

  public allowEdit(allowVal: string) {

    let selMenu: MenuResponse = new MenuResponse();
    selMenu = this.cs.sharedService.getSharedData(MenuResponse.SHARED_DATA, false);
    selMenu.GetMenuEntriesList = allowVal === 'basic' ? this.basicDetailsSubMenu : this.addressSubMenu;
    this.cs.sharedService.setSharedData(selMenu, MenuResponse.SHARED_DATA);

    if (allowVal === 'basic') {
      this.transactionNo++;
      // tslint:disable-next-line: max-line-length
      this.cs.sharedService.setSharedData({ dirfromNotificationPage: false, submitEITObjList: undefined, transNo: this.transactionNo }, 'AddEITData');
      this.openAddBasicDetails();
    } else {
      this.openAddAddress();
    }
  }

  public disableEdit(disableVal) {
    switch (disableVal) {
      case 1:
        this.editBasic = false;
        break;
      case 2:
        this.editAddress = false;
        break;
    }
  }

  async presentModal(source: string) {
    console.log(source);
    const modal = await this.modalController.create({
      component: EditDetailProfileComponent,
      cssClass: 'my-custom-modal-css',
      componentProps:{ sourceName: source}
    });

    modal.onDidDismiss()
      .then((data) => {
        console.log(data);
        if (data.data && data.data.actionClicked === 'next') {
          this.cs.sharedService.setSharedData(data.data, ProfileService.SELECTED_STATUS);
          if (data.data && data.data.data == 1 && source === 'address') {
            this.cs.sharedService.setSharedData(this.addressSubMenu, ProfileService.ADRESS_ENTRIES);
            this.cs.sharedService.setSharedData(this.employeeAdress, ProfileService.EMP_ADDRESS);
            this.cs.sharedService.setSharedData(this.country, ProfileService.COUNTRY);
  
            this.cs.openAddAddress();
          } else if (data.data && data.data.data == 2 && source === 'address') {
            this.cs.openAddAddress();
          } else if (data.data && data.data.data == 1 && source === 'basicDetails') {
            this.cs.openAddBasicDetails('correct');
          } else if (data.data && data.data.data == 2 && source === 'basicDetails') {
            this.cs.openAddBasicDetails('new');
          }
        }
      })
    return await modal.present();
  }

  public updateImageProfile() {
    this.cs.openChangeImagePage();
  }

  public openAddAddress() {
    if (this.addressSubMenu && this.addressSubMenu.UPDATE_BUTTON === 'Y') {
      this.presentModal('address');
    } else {
      this.cs.openAddAddress();
    }
  }

  public openAddBasicDetails() {
    if (this.basicDetailsSubMenu && this.basicDetailsSubMenu.UPDATE_BUTTON === 'Y') {
      this.presentModal('basicDetails');
    } else {
      this.cs.openAddBasicDetails('correct');
    }
  }
}

