import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Router } from '@angular/router';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { Server } from './server';
import { ServerService } from './server.service';

@Component({
    selector: 'app-server',
    templateUrl: './server.component.html',
    styleUrls: ['./server.component.css']
})
export class ServerComponent implements OnInit {
    sendMenuId: number;
    sendPageName = 'Server';
    _menuId: any;
    actionRights: any;
    submitShow: boolean;
    readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
    serverForm: FormGroup;
    servers: Server[] = [];
    serversactive: Server[] = [];
    server: Server;
    deleteResult: boolean;
    postresult: boolean;
    putDResult: boolean;
    serverModalRef: BsModalRef;
    operation: string;
    userid: number;
    serverid: number;
    submitted = false;
    active: number;
    unamePattern: string;
    confmsg: string;
    p = 1; searchText: string;
    itemsPerPage = 10;
    config: ModalOptions = {
        backdrop: 'static',
        keyboard: false,
        animated: true,
        class: 'modal-dialog-centered',
        ignoreBackdropClick: true
    };
    showall = true;
    showallstatus = false;
    key = 'server';
    reverse = false;
    servertypelist: []; 
    constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
        private formBuilder: FormBuilder, private modalService: BsModalService, private serverservice: ServerService) {
         // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
        localStorage.setItem('Server_menuid', this.router.getCurrentNavigation().extras.state.menuid);
        localStorage.setItem('Server_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
      } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('Server_userRights');
      }
    }

    ngOnInit() {
        this.serverForm = this.formBuilder.group({
            serverid: [''],
            server: ['', [Validators.required]],

            servertypeid: [0], 
            ipaddress: [''],
            username: [''],
            password: [''],
            domain: [''],
            impersonate: [''],
            root_path: [''],

            active: ['']
        });
        this.searchText = '';
        this.getAll();
        this.GetServerType();
        this.getUserRights(); 
        // for action rights
        // this.readOnly = true;
        // this.add = true;
        // this.edit = true;
        // this.delete = true;
        // this.submitShow = true;
        // this.getActionRightsList();
    }
 // function to get user rights
 getUserRights() {
    const btnToEnable = JSON.parse(this.actionRights);
    if (btnToEnable.length > 0) {
      this.readOnly = true;
      btnToEnable.forEach(d => {
        if (d !== undefined) {
          if (d === 2) {
            this.add = true;
          } else if (d === 3) {
            this.edit = true;
          } else if (d === 4) {
            this.delete = true;
          }
        }
      });
    }
  }

    getactiveinactive(showallp) {
        this.serversactive = [];
        this.showall = showallp;
        this.showallstatus = showallp;
        if (this.showall === true) {
            this.showall = false;
            this.servers.forEach(data => {
                if (data.active === 1) {
                    this.serversactive.push(data);
                }
            });
            this.servers = [];
            this.servers = this.serversactive;
        } else {
            this.showall = true;
            this.servers = [];
            this.getAll();
        }
    }

    clearForm() {
       this.serverModalRef.hide();
    }

    sort(key) {
        this.key = key;
        this.reverse = !this.reverse;
    }


    getAll() {
        this.servers = [];
        this.serversactive = [];
        this.serverservice.Get().subscribe(res => {
            if (res[0] != null && res[0] !== undefined) {
                this.servers = JSON.parse(res[0]);
                if (this.showallstatus === true) {
                    this.servers.forEach(data => {
                        if (data.active === 1) {
                            this.serversactive.push(data);
                        }
                    });
                    this.servers = [];
                    this.servers = this.serversactive;
                }
            }
        }, error => { this.toastr.error('Error while getting data'); });

    }

    get g() { return this.serverForm.controls; }

    Post(server: Server) {
        this.submitted = true;

        if ((server.server.trim() === undefined) || (server.server.trim() === '')) {
            this.toastr.error('Server should not be empty');
            return;
        }

        const _impersonate = server.impersonate.toString();
        // It will return as true if checked else sometimes empty so this below condition will solve the issue
        if (_impersonate === '' || _impersonate === 'false') {
            server.impersonate = 0;
        } else if (server.impersonate.toString() === 'true') {
            server.impersonate = 1;
        }

        let msg = null;

        this.userid = +localStorage.getItem('userid');
        server.server = server.server.trim();
        server.servertypeid = +server.servertypeid;
        if (this.operation === 'add') {

            server.createdby = this.userid;
            msg = 'Record Added Successfully';
            this.serverservice.Post(server).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.serverModalRef.hide();
                            this.getAll();
                            this.toastr.success('Data added successfully');
                            this.clearForm();
                        } else { this.toastr.warning('Record already exists.'); }
                    }
                }
            },
                error => {
                    this.toastr.error('Error while doing the operation');
                    this.postresult = false;
                });
        } else if (this.operation = 'update') {
            this.submitShow = true;
            server.updatedby = this.userid;
            msg = 'Record updated successfully';
            this.serverservice.Put(server).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.serverModalRef.hide();
                            this.getAll();
                            this.toastr.success('Data updated successfully');
                            this.clearForm();
                        } else { this.toastr.warning('Record already exists.'); }
                    }
                }
            },
                error => {
                    this.toastr.error('Error while doing the operation');
                    this.postresult = false;
                });
        }

        this.submitted = false;
    }

    ChangeActive(e) {
        if (e.currentTarget.checked) {
            this.serverForm.controls['active'].setValue(1);
        } else {
            this.serverForm.controls['active'].setValue(0);
        }
    }

    OpenConfirmTemplate(server, template: TemplateRef<any>) {
        if (server.active === 0) {
            this.confmsg = 'activate';
        } else {
            this.confmsg = 'deactivate';
        }
this.dialogService.addDialog(CommondialogComponent,
            {
                title: 'Please Confirm',
                message: 'Are you sure you want to ' + this.confmsg + ' this record ?',
                hclass: 'modelsuccess',
                oktext: 'Yes',
                canceltext: 'No',
                okshow: true,
                cancelshow: true
            }).subscribe((isConfirmed) => {
                if (isConfirmed) {
                    this.server = server;

                    this.Delete();

                }

            });

    }

    Delete() {
        let msg;
        if (this.server.active === 0) {
            this.server.active = 1;
            msg = 'Record activated successfully';
        } else {
            this.server.active = 0;
            msg = 'Record deactivated successfully';
        }
        this.userid = +localStorage.getItem('userid');
        this.server.updatedby = this.userid;
        this.serverservice.Delete(this.server).subscribe(res => {
            this.toastr.success(msg);
            this.getAll();
        },
            error => { this.deleteResult = false; });

    }

    hidePopup() {
        this.serverModalRef.hide();
    }

    openServerModal(template: TemplateRef<any>, type, server?: Server) {

        this.operation = type;

        if (type === 'update') {
            this.serverForm.controls['serverid'].setValue(server.serverid);
            this.serverForm.controls['server'].setValue(server.server);
            this.serverForm.controls['active'].setValue(server.active);

            this.serverForm.controls['servertypeid'].setValue(server.servertypeid);
            this.serverForm.controls['ipaddress'].setValue(server.ipaddress);
            this.serverForm.controls['username'].setValue(server.username);
            this.serverForm.controls['password'].setValue(server.password);
            this.serverForm.controls['domain'].setValue(server.domain);
            this.serverForm.controls['impersonate'].setValue(server.impersonate);
            this.serverForm.controls['root_path'].setValue(server.root_path);

            this.server = server;
        }
        if (type === 'add') {
            this.serverForm.controls['serverid'].setValue(0);
            this.serverForm.controls['server'].setValue('');
            this.serverForm.controls['active'].setValue(1);

            this.serverForm.controls['servertypeid'].setValue(0);  
            this.serverForm.controls['ipaddress'].setValue('');
            this.serverForm.controls['username'].setValue('');
            this.serverForm.controls['password'].setValue('');
            this.serverForm.controls['domain'].setValue('');
            this.serverForm.controls['impersonate'].setValue('');
            this.serverForm.controls['root_path'].setValue('');
        }
        this.serverModalRef = this.modalService.show(template, this.config);

        const aa = document.getElementsByClassName('modal-content');
        aa[0].classList.remove('modal-content');

    }
    GetServerType() {
        this.servertypelist = [];
        this.serverservice.GetServerType().subscribe(
          res => {
            if (res[0] != null && res[0] !== undefined) {
              this.servertypelist = JSON.parse(res[0]);
            }
          });
      }

}
