import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Department } from 'src/app/masters/department/department';
import { User } from 'src/app/masters/user/user';
import { Userrolemapping } from '../userrolemapping/userrolemapping';
import { Role } from 'src/app/masters/role/role';
import { DualListComponent } from 'angular-dual-listbox';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { RoleService } from 'src/app/masters/role/role.service';
import { DepartmentService } from 'src/app/masters/department/department.service';
import { UserService } from 'src/app/masters/user/user.service';
import { UserrolemappingService } from '../userrolemapping/userrolemapping.service';
import { MailtemplateService } from 'src/app/masters/mailtemplate/mailtemplate.service';
import { UseremailmappingService } from './useremailmapping.service';
import { Useremailmapping } from './useremailmapping';
import { Router } from '@angular/router';

@Component({
  selector: 'app-useremailmapping',
  templateUrl: './useremailmapping.component.html',
  styleUrls: ['./useremailmapping.component.css']
})


export class UseremailmappingComponent implements OnInit {
  userRoleForm: FormGroup;
  departments: Department[] = [];
  userList: User[] = [];
  selectedUserList: Userrolemapping[] = [];
  orgselectedUserList: Userrolemapping[] = [];

  roles: Role[] = [];
  departmentid: number;
  mailtemplateid: number;
  userid: number;
  Useremail: Useremailmapping;
  dropdownSettings = {};
  filter = '';
  formTocuhed = false;
  mailtemplatemappingid = 0;
  format = {
    add: 'Add', remove: 'Remove', all: 'All', none: 'None',
    direction: DualListComponent.LTR, draggable: true, filter: true
  };

  _mailTemplateList: any = [];
  _mailTemplateListTmp: any = [];
  _mailTemplateListactive: any = [];
  actionRights: any;
  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private SpinnerService: NgxSpinnerService,
    private toastr: ToastrService,
    private roleService: RoleService,
    private departmentservice: DepartmentService,
    private userservice: UserService,
    private userrolemappingService: UserrolemappingService,
    private mailtemplateService: MailtemplateService,
    private useremailmappingService: UseremailmappingService,
  ) { 

    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('UserMailMapping_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('UserMailMapping_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('UserMailMapping_userRights');
    }
  }

  ngOnInit() {
    this.userRoleForm = this.formBuilder.group({
      mailtemplatemappingid: [0],
      mailtemplateid: [0],
      mailtemplatename: [0],
      departmentid: [0],
      extermailids: '',
      userid: [],
      active: [1],
    });

    this.dropdownSettings = {
      singleSelection: false,
      idField: 'userid',
      textField: 'firstname',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 5,
      allowSearchFilter: true
    };
    this.formTocuhed = false;
    this.userid = +localStorage.getItem('userid');
    this.loadExisitingMailTemplateList();
  }

  destinationChange(item: Userrolemapping[]) {
    if (this.departmentid !== 0) {
      this.orgselectedUserList = this.orgselectedUserList.filter(s => s.departmentid !== this.departmentid);
      item.forEach(element => {
        this.orgselectedUserList.push(element);
      });
    } else {
      this.orgselectedUserList = [];
      item.forEach(element => {
        this.orgselectedUserList.push(element);
      });
    }
    this.formTocuhed = true;
  }

  GetUser() {
    this.SpinnerService.show();
    this.userList = [];
    this.departmentid = +this.userRoleForm.value.departmentid;
    this.userservice.Get().subscribe(res => {
      this.userList = JSON.parse(res[0]);
      if(this.userList) {
      this.userList = this.userList.filter(u => u.active === 1);
      }
      this.SpinnerService.hide();
      this.selectedUserList = this.orgselectedUserList;
    }, error => {
      this.toastr.error('Error while getting users data');
    });
  }

  GetMappedUserList() {
    // this.SpinnerService.show();
    this.mailtemplateid = +this.userRoleForm.value.mailtemplateid;
    if (this.mailtemplateid) {
      this.useremailmappingService.getMappedUserList(this.mailtemplateid).subscribe(res => {
        this.GetUser();
        if (res.body[0]) {
          this.SpinnerService.hide();
          this.mailtemplatemappingid = JSON.parse(res.body[0])[0].mailtemplatemappingid;
          this.userRoleForm.controls['extermailids'].setValue(JSON.parse(res.body[0])[0].extermailids);
          this.selectedUserList = JSON.parse(res.body[0])[0].userid;
          this.orgselectedUserList = JSON.parse(res.body[0])[0].userid;
          // if (this.selectedUserList) {
          //     this.selectedUserList = this.selectedUserList.filter(s => s.departmentid === this.departmentid);
          // }
          this.SpinnerService.hide();
        } else {
          this.mailtemplatemappingid = 0;
          this.userRoleForm.controls['extermailids'].setValue('');
          this.SpinnerService.hide();
          this.orgselectedUserList = [];
          this.selectedUserList = [];
          this.SpinnerService.hide();
        }
      }, error => { this.toastr.error('Error while getting data'); });
    } else {
      this.mailtemplatemappingid = 0;
      this.userRoleForm.controls['extermailids'].setValue('');
      this.SpinnerService.hide();
      this.orgselectedUserList = [];
      this.selectedUserList = [];
      this.userList = [];
      this.SpinnerService.hide();
    }
  }

  clear() {
    this.userList = [];
    this.orgselectedUserList = [];
    this.selectedUserList = [];
    this.userRoleForm.controls['mailtemplateid'].setValue(0);
    this.userRoleForm.controls['extermailids'].setValue(0);
  }

  saveUserRole() {
    // this.SpinnerService.show();
    let regxpat = new RegExp(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);
    let externalMailList = [];
    let invalidMailCount = 0;
    if (this.userRoleForm.value.extermailids) {
      if (this.userRoleForm.value.extermailids.trim() != null && this.userRoleForm.value.extermailids.trim() !== '') {
        let b = this.userRoleForm.value.extermailids.split(';');
        b.forEach(element => {
          if (element != '') {
            if (!regxpat.test(element)) {
              invalidMailCount++;
            } else {
              externalMailList.push(element);
            }
          }
        });
      }
    }
    if (invalidMailCount > 0) {
      this.toastr.warning('Please enter valid  external mail id');
      return false;
    }
    this.userRoleForm.value.mailtemplatemappingid = +this.mailtemplatemappingid;
    this.userRoleForm.value.mailtemplateid = +this.userRoleForm.value.mailtemplateid;
    this.userRoleForm.value.extermailids = this.userRoleForm.value.extermailids;
    this.userRoleForm.value.userid = JSON.stringify(this.orgselectedUserList.map(org => ({ userid: org.userid })));
    this.userRoleForm.value.active = 1;
    this.userRoleForm.value.createdby = this.userid;
    this.userRoleForm.value.updatedby = this.userid;
    if (this.mailtemplatemappingid) {
      this.useremailmappingService.Put(this.userRoleForm.value).subscribe(res => {
        this.SpinnerService.hide();
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.GetMappedUserList();
              this.toastr.success('Data added successfully');
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          console.log(error);
          this.toastr.error('Error while doing the operation');
        });
    } else {
      console.log('selectedUserList=', this.userRoleForm.value);
      this.useremailmappingService.Post(this.userRoleForm.value).subscribe(res => {
        this.SpinnerService.hide();
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.GetMappedUserList();
              this.toastr.success('Data added successfully');
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          console.log(error);
          this.toastr.error('Error while doing the operation');
        });
    }
  }

  loadExisitingMailTemplateList() {
    this.SpinnerService.show();
    this._mailTemplateList = [];
    this._mailTemplateListactive = [];
    this._mailTemplateListTmp = [];
    this.mailtemplateService.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this._mailTemplateListTmp = JSON.parse(res[0]);
          this._mailTemplateListTmp.forEach(item => {
            if (item.mailtemplateid !== 0) {
              // pushing the required fields to the list to bind in the grid
              this._mailTemplateList.push({
                mailtemplateid: item.mailtemplateid,
                mailtemplatename: item.mailtemplatename,
                active: item.active
              });
            }
          });
          this._mailTemplateList.forEach(data => {
            if (data.active === 1) {
              this._mailTemplateListactive.push(data);
            }
          });
          this._mailTemplateList = [];
          this._mailTemplateList = this._mailTemplateListactive;
        }
      }
      console.log('this._mailTemplateList=', this._mailTemplateList);
      this.SpinnerService.hide();
    }, error => { this.SpinnerService.hide(); this.toastr.error('Error while getting data'); });
  }
}
