import { Component, OnInit } from '@angular/core';
import { 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 { UserItemTypes } from '../models/userItemTypeRequest';
import { WorklistMainService } from '../service/work-list.main.service';

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

  notificationList = [];
  request = [];
  isChange = false;

  public direction: string;

  constructor(
    public modalController: ModalController,
    public ts: TranslatorService,
    public common: CommonService,
    public workListService: WorklistMainService) {}


  ngOnInit() {
    this.direction = TranslatorService.getCurrentDirection();
    this.workListService.getWorklistNotifications()
    .subscribe((result: any) => {
      this.notificationList = result.GetUserItemTypesList;
      for (let i = 0; i < this.notificationList.length; i++) {
        this.request[i] = {
          P_FYA_ENABLED_FALG: this.notificationList[i].FYA_ENABLED_FALG,
          P_FYI_ENABLED_FLAG: this.notificationList[i].FYI_ENABLED_FLAG,
          P_ITEM_TYPE: this.notificationList[i].ITEM_TYPE,
          ItemID: i
        };
      }
    });
  }

  chnageToggle(toggleValue, type, val) {
    if ( val === 'Y') {
      val = 'N';
    } else if ( val  === 'N') {
      val = 'Y';
    }
    this.notificationList.forEach((el, index) => {
      if ( el.ITEM_TYPE === toggleValue.ITEM_TYPE) {
        if (type === 'FYI') {
          this.request[index].P_FYI_ENABLED_FLAG = val;
        } else if (type === 'FYA') {
          this.request[index].P_FYA_ENABLED_FALG = val;
        }
        this.request[index].ItemID = index;
      }
      this.request[index].P_ITEM_TYPE = el.ITEM_TYPE;
    });
  }

  saveChanges() {
    const body = {
      UpdateItemTypeList: this.request
    };
    this.workListService.updateWorklistNotifications(body)
    .subscribe((result: any) => {
      if (result.UpdateItemTypeSuccessList) {
        if (result.UpdateUserItemTypesList) {
          this.common.greenToastPK('worklist', 'save-successfully');
          this.dismiss();
        } else {
          this.common.redToastPK('worklist', 'save-error');
        }
      } else {
        this.common.redToastPK('worklist', 'save-error');
      }
    });
  }

  public dismiss() {
    this.common.sharedService.setSharedData(false, 'loadWorkList');
    this.common.back();
  }
}
