
import { Component, OnInit, TemplateRef } from '@angular/core';
import { UseraddService } from './useradd.service';
import { User } from '../user/user';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap/modal';
import { FormGroup, Validators, FormBuilder, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DomSanitizer } from '@angular/platform-browser';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { MenurightsComponent } from '../../Shared/menurights/menurights.component';
import { DialogService } from 'ng2-bootstrap-modal';
import { ChangeDetectorRef } from '@angular/core';
import * as $ from 'jquery'; declare let $: any;
import { CommonService } from '../../Shared/commonservice';
import { last } from 'rxjs/operators';
import { NgxSpinnerService } from 'ngx-spinner';
import { RoleService } from '../role/role.service';
import { Department } from '../department/department';
import { DepartmentService } from '../department/department.service';
import { UserService } from '../user/user.service';

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

})
export class UseraddComponent implements OnInit {
  sendMenuId = 1;
  sendPageName = 'User Add';
  _teamList: any = []; _teamListTmp: any = [];
  _databaseList: any = []; _databaseListTmp: any = [];
  _selectedItems: any = [];
  _requestList: any = []; _requestListTmp: any = [];
  _requestdropdownSettings: any = [];
  _requestselectedItems: any = [];
  _mappedMenuActionList: any;
  useridlogin: number;
  _dropdownSettings: any;
  _action: string;
  _userId: number;
  imagepath: any;
  _hidepassword: number;
  textBoxTocuhed: boolean;
  actions = [];
  userForm: FormGroup;
  users: User;
  fileselect = false;
  user: User;
  title: string;
  edituser1: User;
  submitted = false;
  checkedstatus: boolean;
  loading = false;
  _accessrequestid: number;
  _roleList: any = [];
  _roleListactive: any = [];
  actionRights: any;
  departments: Department[] = [];
  userList: User[] = [];
  userdetail: User;
  isremove = 0;
  constructor(
    private router: Router,
    private toastr: ToastrService,
    private SpinnerService: NgxSpinnerService,
    private menucomp: MenurightsComponent,
    private _sanitizer: DomSanitizer,
    // private databaseService: DatabaseService,
    private formBuilder: FormBuilder,
    private useraddservice: UseraddService,
    // private teamService: TeamMgtService,
    private route: ActivatedRoute,
    private cdref: ChangeDetectorRef,
    private dialogService: DialogService,
    private commonService: CommonService,
    private roleService: RoleService,
    private departmentservice: DepartmentService,
    private userservice: UserService,
  ) {
    this._userId = +this.route.snapshot.queryParamMap.get('userid');

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

  ngOnInit() {
    this.userForm = this.formBuilder.group({
      userid: [''],
      firstname: ['', [Validators.required]],
      lastname: ['', [Validators.required]],
      emailid: ['', [Validators.required, Validators.email]],
      roleid: [0, [Validators.required]],
      password: [''],
      // tat_mapping:[''],
      // usermailfoldername:[''],
      menumapped: [''],
      comment: [''],
      ImgFile: [''],
      departmentid: [0],
      authorizerid: [0],
      location: [''],
      contactno: [],
      empid: ['', [Validators.required]],
      actions: new FormArray([])
    });

    this._selectedItems = [];
    this.loadExisitingRoleList();
    this.loadDepartment();
    this.loadUser();
    // $('body').addClass('nav-sm').removeClass('nav-md');
  }

  loadDepartment() {
    this.departments = [];
    this.departmentservice.Get().subscribe(res => {
      this.departments = JSON.parse(res[0]);
      this.departments = this.departments.filter(d => d.active === 1);
    }, error => { this.toastr.error('Error while getting data'); });
  }

  loadUser() {
    this.SpinnerService.show();
    this.userList = [];
    this.userservice.Get().subscribe(res => {
      this.userList = JSON.parse(res[0]);
      this.userList = this.userList.filter(u => u.active === 1);
      this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting users data');
    });
  }
  singlesignon(eve) {
    if (eve.target.value = 0) {
      this._hidepassword = 1;
    } else {
      this._hidepassword = 0;
    }
  }

  ngAfterViewInit() {
    this._userId = +this.route.snapshot.queryParamMap.get('userid');
    if (this._userId > 0) {
      this._selectedItems = [];
      this._requestselectedItems = [];
      this.edituser(this._userId);
      this._action = 'update';
      this.title = 'Update ';
    } else {
      this._action = 'add';
      this.title = 'Add ';
    }
    this.cdref.detectChanges();
  }

  get formdata() { return this.userForm.controls; }

  onFileSelect(fileInput: any) {
    if (fileInput.target.files.length > 0) {
      this.fileselect = true;
      const file = fileInput.target.files[0];
      this.userForm.get('ImgFile').setValue(file);
      const reader = new FileReader();
      reader.readAsDataURL(fileInput.target.files[0]);
      reader.onload = (_event) => {
        this.imagepath = reader.result;
      };
      this.isremove = 0;
    }
  }

  getimageedit(filename: string): any {

    this.useraddservice.GetImage(filename).subscribe(res => {
      if (res.type !== 'text/plain') {
        const objectURL = 'data:image/jpeg;base64,' + res.image;
        this.imagepath = this._sanitizer.bypassSecurityTrustUrl(objectURL);
      }
    }, error => { });

  }
  changeUserType() {

    const a = $('#userType option:selected').text();
    if (a === 'SSO User') {
      document.getElementById('password').style.display = 'none';
    } else {
      // this.userType = true;
      // this.userType = true;

      if (this.edituser1 != null) {
        if (this.edituser1.passwordhash != null) {
          document.getElementById('password').style.display = 'none';
        } else {
          document.getElementById('password').style.display = 'block';
        }
      } else {
        document.getElementById('password').style.display = 'block';
      }
    }
  }

  Postuser(user: User) {
    debugger;
    this.submitted = true;
    if (this.userForm.valid) {
      this.useridlogin = +localStorage.getItem('userid');
      const groupDatabaseMapped = {};
      const grouprequestmapped = {};
      if (+user.teamid === 0) {
        this.toastr.error('Team should get selected');
        return;
      }
      if (+user.roleid === 0) {
        this.toastr.error('User role should get selected');
        return;
      }
      if (+user.departmentid === 0) {
        this.toastr.error('User department should get selected');
        return;
      }
      this.checkedstatus = this.menucomp.getselectedmenuscheck();
      this._mappedMenuActionList = [];
      this._mappedMenuActionList = this.menucomp.getselectedmenus();
      user.menumapped = JSON.stringify(this._mappedMenuActionList);
      // groupDatabaseMapped['databasemapped'] = this.databaseSaveStructure(this._selectedItems);
      // user.databasemapped = JSON.stringify(groupDatabaseMapped);
      // grouprequestmapped['requestmapped'] = this.requestSaveStructure(this._requestselectedItems);
      // user.requestmapped = JSON.stringify(grouprequestmapped);
      if (this._action === 'add') {
		 if (user.password === '' || user.password === null) {
          this.toastr.warning('Enter the Password');
          return;
        }


        if (user.tat_mapping === 0 || user.tat_mapping === null) {
          this.toastr.warning('Enter the Tat Mapping');
          return;
        }

        // if (user.usermailfoldername === '' || user.usermailfoldername === null) {
        //   this.toastr.warning('Enter the User Mail Folder Name');
        //   return;
        // }


        this.SpinnerService.show();
        user.userid = 0;
        user.createdby = this.useridlogin;
        user.active = 1;
        user.isremove = this.isremove;
        const formData = new FormData();
        formData.set('ImgFile', this.userForm.get('ImgFile').value);
        for (let key in user) {
          formData.set(key, user[key]);
        }

        // this.commonService.sendemail(user.emailid, "useradd").toPromise().then(res => {
        this.useraddservice.Post(formData).subscribe(
          (res) => {
            if (res.body !== 0) {
              this.toastr.success('User added successfully');
              this.router.navigate(['/masters/user']);
              this.clearForm();
            } else { this.toastr.warning('User already exists '); }
          }, error => {
            this.SpinnerService.hide();
            this.toastr.error(error.error);
          });
      }

      // updating the user information
      if (this._action === 'update') {
        this.SpinnerService.show();
        user.updatedby = this.useridlogin;
        user.userid = this._userId;
        user.isremove = this.isremove;
        if (this.edituser1 != null) {
          //  user.accessrequestid = this.edituser1.accessrequestid;
        }
        const formData = new FormData();
        formData.set('ImgFile', this.userForm.get('ImgFile').value);
        for (var key in user) {
          formData.set(key, user[key]);
        }

        this.useraddservice.Put(formData).subscribe(
          (res) => {
            if (res.body !== 0) {
              this.toastr.success('User updated successfully');
              this.router.navigate(['/masters/user']);
              this.clearForm();
            } else { this.toastr.warning('User already exists'); }
          }, error => {
            this.SpinnerService.hide();
            this.toastr.error(error.error);
          });
      }   
    } else {
      debugger;
      this.submitted = false;
      if (this.userForm.value.firstname == null || this.userForm.value.firstname == undefined || this.userForm.value.firstname == '') {
        this.toastr.warning('Enter the Firstname');
        return;
      }
      if (this.userForm.value.lastname == null || this.userForm.value.lastname == undefined || this.userForm.value.lastname == '') {
        this.toastr.warning('Enter the Lastname');
        return;
      }
      if (this.userForm.value.emailid == null || this.userForm.value.emailid == undefined || this.userForm.value.emailid == '') {
        this.toastr.warning('Enter the Email id');
        return;
      }
      if (this.userForm.value.empid == null || this.userForm.value.empid == undefined || this.userForm.value.empid == '') {
        this.toastr.warning('Enter the Employee id');
        return;
      }
      if (this.userForm.value.roleid == null || this.userForm.value.roleid == undefined || this.userForm.value.roleid == 0) {
        this.toastr.warning('Select the Role');
        return;
      }
      if (this.userForm.value.departmentid == null || this.userForm.value.departmentid == undefined || this.userForm.value.departmentid == 0) {
        this.toastr.warning('Select the Department');
        return;
      }
      // if (this.userForm.value.tat_mapping == null || this.userForm.value.tat_mapping == undefined || this.userForm.value.tat_mapping == 0) {
      //   this.toastr.warning('Enter the Tat Mapping');
      //   return;
      // }
      // if (this.userForm.value.usermailfoldername == null || this.userForm.value.usermailfoldername == undefined || this.userForm.value.usermailfoldername == 0) {
      //   this.toastr.warning('Enter the User Mail Folder Name');
      //   return;
      // }
    }
    
    this.submitted = false;
  }
  // form save json structure for database
  databaseSaveStructure(list) {
    const temp = [];
    if (list.length > 0) {
      list.forEach(item => {
        temp.push({ databaseid: item.databaseid });
      });
    }
    return temp;
  }

  requestSaveStructure(list) {
    const temp = [];
    if (list.length > 0) {
      list.forEach(item => {
        temp.push({ requesttypeid: item.requesttypeid });
      });
    }
    return temp;
  }

  clearForm() {

    this.submitted = false;
    this._selectedItems = [];
    this.userForm.reset();
    this.userForm.controls['roleid'].setValue(0);
    if (this._action === 'update') {
      this.router.navigate(['masters/user']);
    }

  }

  LoadExisitingRequestTypeList() {
    this.useraddservice.GetRequesttype().toPromise().then(res => {
      const allData = res;
      this._requestListTmp = [];
      allData.forEach(data => {
        if (data.active !== 0) {
          this._requestListTmp.push({ requesttypeid: data.requesttypeid, requesttype: data.requesttype });
        }
      });
      this._requestList = [];
      this._requestdropdownSettings = {
        singleSelection: false,
        idField: 'requesttypeid',
        textField: 'requesttype',
        selectAllText: 'Select All',
        unSelectAllText: 'UnSelect All',
        itemsShowLimit: 7,
        allowSearchFilter: true
      };
      this._requestList = JSON.parse(JSON.stringify(this._requestListTmp));
      if (this.edituser1 != null) {
        if (this._requestListTmp.length > 0) {
          if (JSON.parse(this.edituser1.requestmapped) != null) {
            this._requestselectedItems = this.requestMultiSelectStrucuture((
              JSON.parse(this.edituser1.requestmapped)).requestmapped, this._requestListTmp);
          } else {
            this._requestselectedItems = [];
          }
        }
      }
    }, error => { this.toastr.error('error while getting Request type Data'); });
  }

  chkArrayTouched() {
    this.textBoxTocuhed = true;
  }


  Backtouserlist() {

    if ((this.edituser1 != null) && ((this.userForm.touched === true) || (this.textBoxTocuhed === true) || (this.fileselect === true))) {
      this.confirmation(this.edituser1.userid);

    } else {
      this.router.navigate(['/masters/user']);
    }
  }

  confirmation(userid) {
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Confirmation',
        message: 'Would you like to save changes? ',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.Postuser(this.userForm.value);
        } else {
          this.router.navigate(['/masters/user']);
        }
      });

  }
  // form valid mail structure suit for  multi select list
  formMultiSelectStrucuture(mappedList, dbList) {
    const tempList = [];
    if (mappedList.length !== 0) {
      dbList.forEach((d) => {
        mappedList.forEach((data, ind) => {
          if (data.databaseid === d.databaseid) {
            tempList.push({
              databaseid: d.databaseid, database: d.database
            });
          }
        });
      });
    }
    mappedList = [];
    mappedList = tempList;
    return tempList;
  }


  // form valid mail structure suit for  multi select list
  requestMultiSelectStrucuture(mappedList, requestList) {
    const tempList = [];
    if (mappedList.length !== 0) {
      requestList.forEach((d) => {
        mappedList.forEach((data, ind) => {
          if (data.requesttypeid === d.requesttypeid) {
            tempList.push({
              requesttypeid: d.requesttypeid, requesttype: d.requesttype
            });
          }
        });
      });
    }
    mappedList = [];
    mappedList = tempList;
    return tempList;
  }

  loadExisitingRoleList() {
    this.SpinnerService.show();
    this._roleList = [];
    this._roleListactive = [];
    this.roleService.Get().subscribe(res => {
      if (res !== undefined && res != null && res[0] !== undefined && res[0] != null) {
        if (JSON.parse(res[0]).length > 0) {
          this._roleList = JSON.parse(res[0]);
          this._roleList.forEach(data => {
            if (data.active === 1) {
              this._roleListactive.push(data);
            }
          });
          this._roleList = [];
          this._roleList = this._roleListactive;
        }
      }
      this.SpinnerService.hide();
    }, error => { this.SpinnerService.hide(); this.toastr.error('Error while getting role data'); });
  }


  // click event for edit icon in the grid
  edituser(userid) {
    this._action = 'update';
    this.userForm.value.userid = userid;
    this.userForm.value.databasemapped = '';
    this.useraddservice.GetById(userid).subscribe(
      (res) => {
        this.users = JSON.parse(res[0].j)[0];
        (this.users.roleid) ? this.userForm.controls['roleid'].setValue(this.users.roleid) :
          this.userForm.controls['roleid'].setValue(0);
        this.userForm.controls['userid'].setValue(this.users.userid);
        this.userForm.controls['firstname'].setValue(this.users.firstname);
        this.userForm.controls['lastname'].setValue(this.users.lastname);
        this.userForm.controls['emailid'].setValue(this.users.emailid);
        this.userForm.controls['empid'].setValue(this.users.empid);
        this.userForm.controls['password'].setValue(this.users.password);
        this.userForm.controls['departmentid'].setValue(this.users.departmentid);
        this.userForm.controls['authorizerid'].setValue(this.users.authorizerid);
        this.userForm.controls['location'].setValue(this.users.location);
        this.userForm.controls['contactno'].setValue(this.users.contactno);
        // this.userForm.controls['tat_mapping'].setValue(this.users.tat_mapping);
        // this.userForm.controls['usermailfoldername'].setValue(this.users.usermailfoldername);

        if (this.users.profileimagepath != null) {
          this.imagepath = this.getimageedit(this.users.profileimagepath);

        }
        this.userForm.controls['comment'].setValue(this.users.comment);
        this.SpinnerService.hide();

      }, error => {
        this.SpinnerService.hide();
      });
  }
  clearImage() {
    this.isremove = 1;
    this.imagepath = '';
    this.userForm.get('ImgFile').setValue('');
  }
}

