import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Track } from './track';
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 { TrackService } from './track.service';

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

export class TrackComponent implements OnInit {

  sendMenuId: number;
  sendPageName = 'Track';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly = false; add = false; edit = false; delete = false;
  trackForm: FormGroup;
  tracks: Track[] = [];
  tracksactive: Track[] = [];
  track: Track;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  trackModalRef: BsModalRef;
  operation: string;
  userid: number;
  trackid: 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 = 'trackname';
  reverse = false;

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

  ngOnInit() {
    this.trackForm = this.formBuilder.group({
      trackid: [''],
      trackname: ['', [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.tracksactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.tracks.forEach(data => {
        if (data.active === 1) {
          this.tracksactive.push(data);
        }
      });
      this.tracks = [];
      this.tracks = this.tracksactive;
    } else {
      this.showall = true;
      this.tracks = [];
      this.getAll();
    }
  }

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

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


  getAll() {
    this.tracks = [];

    this.trackservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.tracks = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.tracks = this.tracks.filter(y => y.active === 1);

        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(track: Track) {
    this.submitted = true;

    if ((track.trackname.trim() === undefined) || (track.trackname.trim() === '')) {
      this.toastr.error('Track name should not be empty');
      return;
    }

    let msg = null;

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

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

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

          this.Delete();

        }

      });

  }

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

  }

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

  openTrackModal(template: TemplateRef<any>, type, track?: Track) {

    this.operation = type;

    if (type === 'update') {
      this.trackForm.controls['trackid'].setValue(track.trackid);
      this.trackForm.controls['trackname'].setValue(track.trackname);
      this.trackForm.controls['active'].setValue(track.active);

      this.track = track;
    }
    if (type === 'add') {
      this.trackForm.reset();
      this.trackForm.controls['trackid'].setValue(0);
      this.trackForm.controls['active'].setValue(1);
    }
    this.trackModalRef = this.modalService.show(template, this.config);

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

  }

}
