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 { Customer } from './customer';
import { CustomerService } from './customer.service';

@Component({
    selector: 'app-customer',
    templateUrl: './customer.component.html',
    styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
    sendMenuId: number;
    sendPageName = 'Customer';
    // action rights
    _menuId: any;
    _actionRights: any;
    readOnly = false; add = false; edit = false; delete = false;
    customerForm: FormGroup;
    customers: Customer[] = [];
    customersactive: Customer[] = [];
    customer: Customer;
    deleteResult: boolean;
    postresult: boolean;
    putDResult: boolean;
    customerModalRef: BsModalRef;
    operation: string;
    userid: number;
    customerid: 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 = 'customer'; // set default
    reverse = false;
    actionRights: any;
    constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
        private formBuilder: FormBuilder, private modalService: BsModalService, private customerservice: CustomerService) {
        // get rights for the logged in user for the particular component
        if (this.router.getCurrentNavigation().extras.state !== undefined) {
            localStorage.setItem('Customer_menuid', this.router.getCurrentNavigation().extras.state.menuid);
            localStorage.setItem('Customer_userRights', this.router.getCurrentNavigation().extras.state.action);
            this.actionRights = [];
            this.actionRights = this.router.getCurrentNavigation().extras.state.action;
        } else {
            this.actionRights = [];
            this.actionRights = localStorage.getItem('Customer_userRights');
        }
    }

    ngOnInit() {
        this.customerForm = this.formBuilder.group({
            customerid: [''],
            customername: ['', [Validators.required]],
            address: [''],
            email: [''],
            contactnumber: [''],
            active: [''],
            iconnectcode: ['']
        });
        this.searchText = '';
        this.getAll();
        // for action rights
        this.getUserRights();
    }

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

    // 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;
                    }
                }
            });
        }
    }

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

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


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

    }

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

    Post(customer: Customer) {

        this.submitted = true;

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

        let msg = null;

        this.userid = +localStorage.getItem('userid');
        customer.customername = customer.customername.trim();
        if(customer.contactnumber){
            customer.contactnumber = customer.contactnumber.toString();
        }
        if (this.operation === 'add') {

            customer.createdby = this.userid;
            msg = 'Record Added Successfully';
            this.customerservice.Post(customer).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.customerModalRef.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') {
            customer.updatedby = this.userid;
            msg = 'Record updated successfully';
            this.customerservice.Put(customer).subscribe(res => {
                if (res.status === 200) {
                    if (res !== undefined) {
                        if (res.body !== 0) {
                            this.customerModalRef.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.customerForm.controls['active'].setValue(1);
        } else {
            this.customerForm.controls['active'].setValue(0);
        }
    }

    OpenConfirmTemplate(customer) {
        if (customer.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.customer = customer;

                    this.Delete();

                }

            });

    }

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

    }

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

    openCustomerModal(template: TemplateRef<any>, type, customer?: Customer) {

        this.operation = type;

        if (type === 'update') {
            this.customerForm.controls['customerid'].setValue(customer.customerid);
            this.customerForm.controls['customername'].setValue(customer.customername);
            this.customerForm.controls['address'].setValue(customer.address);
            this.customerForm.controls['email'].setValue(customer.email);
            this.customerForm.controls['contactnumber'].setValue(customer.contactnumber);
            this.customerForm.controls['iconnectcode'].setValue(customer.iconnectcode);
            this.customerForm.controls['active'].setValue(customer.active);
            this.customer = customer;
        }
        if (type === 'add') {
            this.customerForm.controls['customerid'].setValue(0);
            this.customerForm.controls['customername'].setValue('');
            this.customerForm.controls['address'].setValue('');
            this.customerForm.controls['email'].setValue('');
            this.customerForm.controls['contactnumber'].setValue('');
            this.customerForm.controls['iconnectcode'].setValue(0);
            this.customerForm.controls['active'].setValue(1);
        }
        this.customerModalRef = this.modalService.show(template, this.config);

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

    }

}
