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

@Component({
  selector: 'app-feature',
  templateUrl: './feature.component.html',
  styleUrls: ['./feature.component.css']
})
export class FeatureComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Filemode';
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  metadataForm: FormGroup;
  metadatas: Feature[] = [];
  feature: Feature;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  metadataModalRef: BsModalRef;
  operation: string;
  userid: number;
  metadataid: 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 = 'mdata';
  reverse = false;
  appurlData: Feature[] = [];
  constructor(
    private featureservice: FeatureService,
    private appurlservice: AppurlService,
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Feature_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Feature_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Feature_userRights');
    }
  }

  ngOnInit(): void {
    this.metadataForm = this.formBuilder.group({
      metadataid: [''],
      mdata: ['', [Validators.required]],
      appurlid: [0],
      active: ['']
    });
    this.searchText = '';
    this.showallstatus = true;
    this.getAll();
    this.getUserRights();
    this.getAppUrls();
  }
  // 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.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.metadatas = this.metadatas.filter(y => y.active === 1);
      // this.metadatas = [];
      // this.metadatas = this.metadatasactive;
    } else {
      this.showall = true;
      this.metadatas = [];
      this.getAll();
    }
  }

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

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

  getAll() {
    this.metadatas = [];
    this.featureservice.Get().subscribe(res => {
      this.metadatas = JSON.parse(res[0]);
      console.log('this.metadatas=', this.metadatas);
      if (this.showallstatus === true) {
        this.metadatas = this.metadatas.filter(y => y.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(feature: Feature) {

    this.submitted = true;
    // stop here if form is invalid
    if ((feature.mdata.trim() === undefined) || (feature.mdata.trim() === '')) {
      this.toastr.error('feature should not be empty');
      return;
    }
    if ((feature.appurlid === 0)) {
      this.toastr.error('appurl should not be empty');
     return;
    } 
    let msg = null;
    this.userid = +localStorage.getItem('userid');
    feature.mdata = feature.mdata.trim();
    feature.appurlid = +feature.appurlid;
    if (this.operation === 'add') {
      feature.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.featureservice.Post(feature).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.metadataModalRef.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') {
      feature.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.featureservice.Put(feature).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.metadataModalRef.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.metadataForm.controls['active'].setValue(1);
    } else {
      this.metadataForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(feature, template: TemplateRef<any>) {
    if (feature.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.feature = feature;

          this.Delete();
        }
      });
  }

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

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

  openmetadataModal(template: TemplateRef<any>, type, feature?: Feature) {
    this.operation = type;
    if (type === 'update') {
      this.metadataForm.controls['metadataid'].setValue(feature.metadataid);
      this.metadataForm.controls['mdata'].setValue(feature.mdata);
      this.metadataForm.controls['active'].setValue(feature.active);
      this.metadataForm.controls['appurlid'].setValue(feature.appurlid);
      this.feature = feature;
    }
    if (type === 'add') {
      this.metadataForm.controls['metadataid'].setValue(0);
      this.metadataForm.controls['mdata'].setValue('');
      this.metadataForm.controls['active'].setValue(1);
      this.metadataForm.controls['appurlid'].setValue(0);
    }
    this.metadataModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');

  }
  getAppUrls() {
    this.appurlservice.Get().subscribe(res => {
      if (res.status === 200) {
        this.appurlData = JSON.parse( res.body[0]);
        this.appurlData = this.appurlData.filter(e => e.active === 1);
        // this.appurlData = res
      }

    }, err => {
      this.toastr.error('Error while geting apprls')
    })
  }
}