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

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

export class OutlineComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Outline';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly = false; add = false; edit = false; delete = false;
  outlineForm: FormGroup;
  outlines: Outline[] = [];
  outlinesactive: Outline[] = [];
  outline: Outline;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  outlineModalRef: BsModalRef;
  operation: string;
  userid: number;
  outlineid: 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 = 'outlinename';
  reverse = false;

  constructor(
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private outlineservice: OutlineService,
    private outlineconfigurationservice: OutlineconfigurationService,
  ) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Outline_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Outline_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Outline_userRights');
    }
  }

  ngOnInit() {
    this.userid = +localStorage.getItem('userid');
    this.outlineForm = this.formBuilder.group({
      outlineid: [''],
      outlinename: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
    this.getUserRights();
  }
  // 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.outlinesactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.outlines.forEach(data => {
        if (data.active === 1) {
          this.outlinesactive.push(data);
        }
      });
      this.outlines = [];
      this.outlines = this.outlinesactive;
    } else {
      this.showall = true;
      this.outlines = [];
      this.getAll();
    }
  }

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

  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  // get all outline details based on user
  getAll() {
    this.outlines = [];
    const inputData = new Object({
      userid: this.userid,
    });
    this.outlineservice.Get(inputData).subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        this.outlines = JSON.parse(res.body[0]);
        console.log('this.outlines=', this.outlines);
        if (this.showallstatus === true) {
          this.outlines = this.outlines.filter(y => y.active === 1);
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

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

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

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

          this.Delete();

        }

      });

  }

  Delete() {
    let msg;
    if (this.outline.active === 0) {
      this.outline.active = 1;
      msg = 'Record activated successfully';
    } else {
      this.outline.active = 0;
      msg = 'Record deactivated successfully';
    }

    this.outline.updatedby = this.userid;
    this.outlineservice.Delete(this.outline).subscribe(res => {
      this.toastr.success(msg);
      this.getAll();
    },
      error => { this.deleteResult = false; });

  }

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

  openOutlineModal(template: TemplateRef<any>, type, outline?: Outline) {

    this.operation = type;

    if (type === 'update') {
      // this.outlineForm.controls['outlineid'].setValue(outline.outlineid);
      // this.outlineForm.controls['outlinename'].setValue(outline.outlinename);
      this.outlineForm.controls['active'].setValue(outline.active);

      this.outline = outline;
    }
    if (type === 'add') {
      this.outlineForm.reset();
      this.outlineForm.controls['outlineid'].setValue(0);
      this.outlineForm.controls['active'].setValue(1);
    }
    this.outlineModalRef = this.modalService.show(template, this.config);

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

  }

  moveToOutlineConfiguration(item) {
    console.log(item);
    const queryParams = {};
    if (!item) {
      this.router.navigate(['/projectconfiguration/outlineconfiguration']);
    } else {
      const inputData = new Object({
        outlineconfigid: item.outlineconfigid
      });
      this.outlineservice.getAllByIdForStatusCheck(inputData).subscribe(resp => {
        const outlinelist = JSON.parse(resp.body[0]);
      //  if (outlinelist) {
       //   this.toastr.error('Job is progress');
      //  } else {
          const navigationExtras: NavigationExtras = {
            queryParams, state: {
              outlineconfigid: item.outlineconfigid,
              projectid: item.projectid,
              projectdid: item.projectdid,
              title: item.title,
              toolsetid: item.toolsetid,
              issmartchart: item.issmartchart,
              newsalert: item.newsalert,
              outlines: this.outlines,
              isnotapplicable:item.isnotapplicable,
              saveAs: false
            }
          };
          this.router.navigate(['/projectconfiguration/outlineconfiguration'], navigationExtras);
       // }
      }, error => { });
    }
  }

  OpenConfirmTemplateForsaveAs(filetype, template: TemplateRef<any>) {
    this.confmsg = 'clone';
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Do you sure you want to ' + this.confmsg + ' this records ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.SaveAs(filetype);
        }
      });
  }

  SaveAs(item) {
    const queryParams = {};
        const inputData = new Object({
          outlineconfigid: item.outlineconfigid
        });
        this.outlineservice.getByID(inputData).subscribe(resp => {
          const outlinedetails = JSON.parse(resp.body[0]);
          console.log('resp=', resp);
          const navigationExtras: NavigationExtras = {
            queryParams, state: {
              outlineconfigid: outlinedetails[0].outlineconfigid,
              projectid: outlinedetails[0].projectid,
              projectdid: outlinedetails[0].projectdid,
              title: outlinedetails[0].title,
              toolsetid: outlinedetails[0].toolsetid,
              issmartchart: outlinedetails[0].issmartchart,
              newsalert: outlinedetails[0].newsalert,
              isnotapplicable: outlinedetails[0].isnotapplicable,
              outlines: this.outlines,
              saveAs: true
            }
          };
          this.router.navigate(['/projectconfiguration/outlineconfiguration'], navigationExtras);
        }, error => { });
  }
}
