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 { Application } from './application';
import { ApplicationService } from './application.service';
import { Feature } from '../feature/feature';
import { FeatureService } from '../feature/feature.service';
import { AppurlService } from '../appurl/appurl.service';

@Component({
  selector: 'app-application',
  templateUrl: './application.component.html',
  styleUrls: ['./application.component.css']
})
export class ApplicationComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Application';
  // action rights
  _menuId: any;
  _actionRights: any;
  submitShow: boolean;
  readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
  applicationForm: FormGroup;
  applications: Application[] = [];
  applicationsactive: Application[] = [];
  application: Application;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  applicationModalRef: BsModalRef;
  operation: string;
  userid: number;
  applicationid: 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 = 'application'; // set default
  reverse = false;
  feature: any[] = [];
  feature1: any[] = [];
  featureactive: Feature[] = [];
  FeatureselectedItems: any = [];
  actionRights: any;
  appurlsData: any[] = [];
  appurlsweb: any[] = [];
  appurlsservice: any[] = [];
  Selserviceurlid = 0;
  SelWeburlid = 0;
  ServiceFeatureselectedItems: any = [];
  WebFeatureselectedItems: any = [];
  constructor(
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private applicationservice: ApplicationService,
    private featureservice: FeatureService,
    private appurlservice: AppurlService
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Application_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Application_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Application_userRights');
    }

  }

  ngOnInit() {
    this.applicationForm = this.formBuilder.group({
      applicationid: [''],
      application: ['', [Validators.required]],
      active: [''],
      isexe: [''],
      isservice: [''],
      iswebapp: [''],
      exepath: [''],
      serviceurl: [''],
      weburl: [''],
      appversion: [''],
      paramss: [''],
      serviceurlid: [0],
      weburlid: [0],
      isallowmultiplefeature: [0],
      isoutlineconfigtemplate: []
    });
    this.searchText = '';
    this.getAll();

    // for action rights
    this.readOnly = true;
    this.add = true;
    this.edit = true;
    this.delete = true;
    this.submitShow = true;
    // this.getActionRightsList();
    this.getAllFeatures();
    this.getApprlsData();
  }

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

  // assigning value from menu rights button
  getActionRightsList() {
    const btnToEnable = JSON.parse(this._actionRights);
    if (btnToEnable.length > 0) {
      btnToEnable.forEach(d => {
        if (d !== undefined) {
          if (d === 1) {
            this.readOnly = true;
          } else if (d === 2) {
            this.readOnly = true;
            this.add = true;
            this.submitShow = true;
          } else if (d === 3) {
            this.readOnly = true;
            this.edit = true;
            //  this.submitShow = true;
          } else if (d === 4) {
            this.readOnly = true;
            this.delete = true;
          }
        }
      });
    }
  }

  clearForm() {
    // for action rights
    if (this.add === true) {
      this.submitShow = true;
    } else {
      this.submitShow = false;
    }
    this.applicationModalRef.hide();
  }

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

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

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

  Post(application: Application) {
    this.ChangeActive();
    this.submitted = true;
    if ((application.application.trim() === undefined) || (application.application.trim() === '')) {
      this.toastr.error('Application should not be empty');
      return;
    }
    let msg = null;
    this.userid = +localStorage.getItem('userid');
    application.application = application.application.trim();
    this.FeatureselectedItems = [];
    this.ServiceFeatureselectedItems.forEach(element => {
      this.FeatureselectedItems.push(element);
    });
    this.WebFeatureselectedItems.forEach(element => {
      this.FeatureselectedItems.push(element);
    });
    application.webappfeature = this.FeatureselectedItems;
    if (+application.weburlid) {
      application.weburl = this.appurlsweb.find(a => a.appurlid === +application.weburlid).appurl;
    }
    if (+application.serviceurlid) {
      application.serviceurl = this.appurlsservice.find(a => a.appurlid === +application.serviceurlid).appurl;
    }
    application.serviceurlid = +application.serviceurlid;
    application.weburlid = +application.weburlid;
    application.isallowmultiplefeature = +application.isallowmultiplefeature;
    if (this.operation === 'add') {
      application.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.applicationservice.Post(application).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.applicationModalRef.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;
      application.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.applicationservice.Put(application).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.applicationModalRef.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;
  }

  ChangeActiveService(e) {
    if (e.currentTarget.checked) {
      this.ServiceFeatureselectedItems.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 1);
    } else {
      this.ServiceFeatureselectedItems.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 0);
    }
  }

  ChangeActiveWeb(e) {
    if (e.currentTarget.checked) {
      this.WebFeatureselectedItems.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 1);
    } else {
      this.WebFeatureselectedItems.filter(f => f.mdata === e.currentTarget.id).map(s => s.active = 0);
    }
  }

  ChangeActive() {
    // e.currentTarget.checked
    if (this.applicationForm.value.active) {
      this.applicationForm.value.active = 1;
    } else {
      this.applicationForm.value.active = 0;
    }

    if (this.applicationForm.value.isexe) {
      this.applicationForm.value.isexe = 1;
    } else {
      this.applicationForm.value.isexe = 0;
    }

    if (this.applicationForm.value.isservice) {
      this.applicationForm.value.isservice = 1;
    } else {
      this.applicationForm.value.isservice = 0;
    }

    if (this.applicationForm.value.iswebapp) {
      this.applicationForm.value.iswebapp = 1;
    } else {
      this.applicationForm.value.iswebapp = 0;
    }
    if (this.applicationForm.value.isoutlineconfigtemplate) {
      this.applicationForm.value.isoutlineconfigtemplate = 1;
    } else {
      this.applicationForm.value.isoutlineconfigtemplate = 0;
    }
  }

  OpenConfirmTemplate(application) {
    if (application.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.application = application;
          this.Delete();
        }
      });
  }

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

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

  openApplicationModal(template: TemplateRef<any>, type, application?: Application) {

    this.operation = type;
    console.log('application=', application);
    if (type === 'update') {
      this.applicationForm.controls['applicationid'].setValue(application.applicationid);
      this.applicationForm.controls['application'].setValue(application.application);
      this.applicationForm.controls['serviceurlid'].setValue(application.serviceurlid ? application.serviceurlid : 0);
      this.applicationForm.controls['weburlid'].setValue(application.weburlid ? application.weburlid : 0);
      this.applicationForm.controls['isallowmultiplefeature'].setValue(application.isallowmultiplefeature);
      if (application.active === 1) {
        this.applicationForm.controls['active'].setValue(1);
      } else {
        this.applicationForm.controls['active'].setValue(0);
      }
      if (application.isexe === 1) {
        this.applicationForm.controls['isexe'].setValue(1);
      } else {
        this.applicationForm.controls['isexe'].setValue(0);
      }
      if (application.isservice === 1) {
        this.applicationForm.controls['isservice'].setValue(1);
      } else {
        this.applicationForm.controls['isservice'].setValue(0);
      }
      if (application.iswebapp === 1) {
        this.applicationForm.controls['iswebapp'].setValue(1);
      } else {
        this.applicationForm.controls['iswebapp'].setValue(0);
      }

      if (application.isoutlineconfigtemplate === 1) {
        this.applicationForm.controls['isoutlineconfigtemplate'].setValue(1);
      } else {
        this.applicationForm.controls['isoutlineconfigtemplate'].setValue(0);
      }
      this.applicationForm.controls['exepath'].setValue(application.exepath);
      this.applicationForm.controls['serviceurl'].setValue(application.serviceurl);
      this.applicationForm.controls['weburl'].setValue(application.weburl);
      this.applicationForm.controls['appversion'].setValue(application.appversion);
      this.applicationForm.controls['paramss'].setValue(application.paramss);
      this.application = application;
      this.ServiceFeatureselectedItems = [];
      this.WebFeatureselectedItems = [];
      // For services features
      if (application.webappfeature) {
        let webfea = this.featureactive;
        webfea = webfea.filter(w => w.appurlid === application.serviceurlid);
        webfea.forEach(element => {
          if ((application.webappfeature.filter(u => u.mdata === element.mdata && element.appurlid === application.serviceurlid)
            .map(i => ({ metadataid: element.metadataid, mdata: element.mdata, active: i.active }))).length > 0) {
            this.ServiceFeatureselectedItems.push((application.webappfeature.filter(u => u.mdata === element.mdata
              && element.appurlid === application.serviceurlid)
              .map(i => ({
                metadataid: element.metadataid,
                mdata: element.mdata,
                active: i.active
              })))[0]);
          } else {
            element.active = 0;
            this.ServiceFeatureselectedItems.push(element);
          }
        });
      } else {
        this.ServiceFeatureselectedItems = this.featureactive.filter(w => w.active === 1 && w.appurlid === application.serviceurlid)
        .map(f => ({
          metadataid: f.metadataid,
          mdata: f.mdata,
          active: 0
        }));
      }

      // For web features
      if (application.webappfeature) {
        let webfea = this.featureactive;
        webfea = webfea.filter(w => w.appurlid === application.weburlid);
        webfea.forEach(element => {
          if ((application.webappfeature.filter(u => u.mdata === element.mdata && element.appurlid === application.weburlid)
            .map(i => ({ metadataid: element.metadataid, mdata: element.mdata, active: i.active }))).length > 0) {
            this.WebFeatureselectedItems.push((application.webappfeature.filter(u => u.mdata === element.mdata
              && element.appurlid === application.weburlid)
              .map(i => ({
                metadataid: element.metadataid,
                mdata: element.mdata,
                active: i.active
              })))[0]);
          } else {
            element.active = 0;
            this.WebFeatureselectedItems.push(element);
          }
        });
      } else {
        this.WebFeatureselectedItems = this.featureactive.filter(w => w.active === 1 && w.appurlid === application.weburlid)
        .map(f => ({
          metadataid: f.metadataid,
          mdata: f.mdata,
          active: 0
        }));
      }

      console.log('this.ServiceFeatureselectedItems=', this.ServiceFeatureselectedItems);
      console.log('this.WebFeatureselectedItems=', this.WebFeatureselectedItems);
    }
    if (type === 'add') {
      this.applicationForm.controls['applicationid'].setValue(0);
      this.applicationForm.controls['application'].setValue('');
      this.applicationForm.controls['active'].setValue(1);
      this.applicationForm.controls['isexe'].setValue(0);
      this.applicationForm.controls['isservice'].setValue(0);
      this.applicationForm.controls['iswebapp'].setValue(0);
      this.applicationForm.controls['exepath'].setValue('');
      this.applicationForm.controls['serviceurl'].setValue('');
      this.applicationForm.controls['weburl'].setValue('');
      this.applicationForm.controls['appversion'].setValue('');
      this.applicationForm.controls['paramss'].setValue('');
      this.applicationForm.controls['isoutlineconfigtemplate'].setValue('');
      this.applicationForm.controls['serviceurlid'].setValue(0);
      this.applicationForm.controls['weburlid'].setValue(0);
      this.applicationForm.controls['isallowmultiplefeature'].setValue(1);
      this.FeatureselectedItems = [];
      this.ServiceFeatureselectedItems = [];
      this.WebFeatureselectedItems = [];
      // this.FeatureselectedItems = this.feature1.map(i => ({
      //   metadataid: i.metadataid,
      //   mdata: i.mdata,
      //   active: 0
      // })
      // );

      console.log('on add this.FeatureselectedItems=', this.FeatureselectedItems);
    }
    this.applicationModalRef = this.modalService.show(template, this.config);

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

  getAllFeatures() {
    this.feature = [];
    this.featureactive = [];
    this.featureservice.Get().subscribe(res => {
      this.feature = JSON.parse(res[0]);
      console.log('this.metadatas=', this.feature);
      this.featureactive = this.feature.filter(f => f.active === 1);
      this.feature1 = [];
      // this.feature1 = this.featureactive.filter(f => f.active === 1&&f.appurlid===urlid);
    }, error => { this.toastr.error('Error while getting data'); });
  }

  getApprlsData() {
    this.appurlservice.Get().subscribe(res => {
      if (res.status === 200) {
        this.appurlsData = JSON.parse(res.body[0]);
        this.appurlsData = this.appurlsData.filter(e => e.active === 1);
        this.appurlsweb = this.appurlsData.filter(e => e.active === 1 && e.urltype === 'weburl');
        this.appurlsservice = this.appurlsData.filter(e => e.active === 1 && e.urltype === 'serviceurl');
      }

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

  ChangeUrl(urlid) {
    this.Selserviceurlid = +urlid.value;
    this.feature1 = this.featureactive.filter(f => (f.appurlid === this.Selserviceurlid)).map(s => ({
      metadataid: s.metadataid,
      mdata: s.mdata,
      active: 0
    }));
    this.ServiceFeatureselectedItems = [];
    this.feature1.forEach(element => {
      this.ServiceFeatureselectedItems.push(element);
    });
  }

  ChangeUrl2(urlid) {
    this.SelWeburlid = +urlid.value;
    this.feature1 = this.featureactive.filter(f => (f.appurlid === this.SelWeburlid)).map(s => ({
      metadataid: s.metadataid,
      mdata: s.mdata,
      active: 0
    }));
    this.WebFeatureselectedItems = [];
    this.feature1.forEach(element => {
      this.WebFeatureselectedItems.push(element);
    });
  }
}
