import { Component, OnInit, Input,TemplateRef,ViewChild } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { UseraddService } from '../../masters/useradd/useradd.service';
import { User } from '../../masters/user/user';
import { ToastrService } from 'ngx-toastr';
import { CommonService } from '../commonservice';
import {  BsModalService, BsModalRef, ModalOptions } from 'ngx-bootstrap/modal';
import { LogoutService } from '../../logout/logout.service';
import { Router } from '@angular/router';
declare var $: any;

@Component({
  selector: 'app-topbar',
  templateUrl: './topbar.component.html',
  styleUrls: ['./topbar.component.css']
})
export class TopbarComponent implements OnInit {
  @Input() menuLength: number;
  @ViewChild("pendinglotinfoTemplate", { static: true })
  pendinglotinfoTemplate: TemplateRef<any>;
  userPreferences: any = [];
  hideAndShowText = 'Hide';
  minAndMaxText = 'Minimize';
  config: ModalOptions = {
    backdrop: "static",
    keyboard: false,
    animated: true,
    class: "modal-dialog-centered",
    ignoreBackdropClick: true,
  };
  pendinglotinfoModalRef: BsModalRef;
  pendinglot:number=0;
  assignlot:number=0;
  constructor(private _sanitizer: DomSanitizer,
    private useraddService: UseraddService,
    private commonService: CommonService,
    private modalService: BsModalService,
    private toastr: ToastrService, 
    private logoutservice: LogoutService
    , private router: Router
    ) { }
  public username = localStorage.getItem('username');
  releaseversion: string;
  url = 'src/assets/js/custom.js';
  public userid = localStorage.getItem('userid');
  public emaiid = localStorage.getItem('emailid');

  public typeOfRole = '';
  imagepath: any;
  user: User;
  ngOnInit() {
    this.useraddService.GetById(+this.userid).subscribe(res => {
      console.log('finalres', res);
      if (res !== undefined) {
        let userData = JSON.parse(res[0].j);
        this.user = userData.find(u => u.userid === +this.userid);
        // console.log(this.user.profileimagepath);
        if (this.user.profileimagepath != null) {
          this.useraddService.GetImage(this.user.profileimagepath).subscribe(res => {
            if (res.type !== 'text/plain') {
              let objectURL = 'data:image/jpeg;base64,' + res.image;
              this.imagepath = this._sanitizer.bypassSecurityTrustUrl(objectURL);
              if (this.imagepath.changingThisBreaksApplicationSecurity === 'data:image/jpeg;base64,') {
                this.useraddService.GetImage('impg.jpg').subscribe(res => {
                  if (res.type !== 'text/plain') {
                    let objectURL = 'data:image/jpeg;base64,' + res.image;
                    this.imagepath = this._sanitizer.bypassSecurityTrustUrl(objectURL);
                  }
                });
              }
            }
          }, error => {
            console.log('asdfasdfasdfas', error);
          });
        } else {
          this.imagepath = 'assets/images/img.png';
        }
        //  console.log( this.imagepath);
      }
    }, error => { });
    this.getuserPreferences();
  }

  toggleclicked() {
    debugger;
    var $BODY = $('body'),
      $SIDEBAR_MENU = $('#sidebar-menu');

    // $(window).resize();
    // console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
      $SIDEBAR_MENU.find('li.active ul').hide();
      $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
      $SIDEBAR_MENU.find('li.active-sm ul').show();
      $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

    $BODY.toggleClass('nav-md nav-sm');

    this.setContentHeight();

    $('.dataTable').each(function () { $(this).dataTable().fnDraw(); });
    return;
  }

  setContentHeight() {
    var $RIGHT_COL = $('.right_col'), $BODY = $('body'), $SIDEBAR_FOOTER = $('.sidebar-footer'),
      $LEFT_COL = $('.left_col'), $FOOTER = $('footer'), $NAV_MENU = $('.nav_menu');
    // reset height
    $RIGHT_COL.css('min-height', $(window).height());

    var bodyHeight = $BODY.outerHeight(),
      footerHeight = $BODY.hasClass('footer_fixed') ? -10 : $FOOTER.height(),
      leftColHeight = $LEFT_COL.eq(1).height() + $SIDEBAR_FOOTER.height(),
      contentHeight = bodyHeight < leftColHeight ? leftColHeight : bodyHeight;

    // normalize content
    contentHeight -= $NAV_MENU.height() + footerHeight;

    $RIGHT_COL.css('min-height', contentHeight);
  }

  getuserPreferences() {

    var obj = {
      userid: +this.userid
    }
    this.commonService.getserPreferences(obj).subscribe(res => {
      if (res.status === 200 && res.body[0])
        this.userPreferences = JSON.parse(res.body[0]);

    }, err => {
      this.toastr.error('error in geting user preferences');

    })
  }

  hideAndShow(event) {
    let a = event.currentTarget.checked;
    let showandhide;

    if (a) {
      this.hideAndShowText = 'Show';

      //optionid=this.optionsList.find(e=>e.option.trim()==='hide'.trim());
      showandhide = 0;
    }
    else {
      this.hideAndShowText = 'Hide';
      //optionid=this.optionsList.find(e=>e.option.trim()==='show'.trim());
      showandhide = 1;
    }
    var obj = {
      userid: +this.userid,
      showandhide: showandhide
    }
    if (this.userPreferences.length === 0) {
      this.commonService.postuserpreference(obj).subscribe(res => {
        this.getuserPreferences();
        this.toastr.success('preference updated successfully');
      }, err => {
        this.toastr.error('error in geting ser preferences');

      })
    }
    if (this.userPreferences.length == 1) {
      this.commonService.UpadateUserPreferences(obj, 'showandhideupdate').subscribe(res => {
        this.getuserPreferences();
        this.toastr.success('preference updated successfully');
      }, err => {
        this.toastr.error('error in geting ser preferences');

      })
    }

  }

  minAndMax(event) {
    let a = event.currentTarget.checked;
    let minandmax;
    if (a) {
      this.minAndMaxText = 'Maximize';
      //optionid=this.optionsList.find(e=>e.option.trim()==='minimize'.trim());
      minandmax = 0
    }
    else {
      this.minAndMaxText = 'Minimize';
      //optionid=this.optionsList.find(e=>e.option.trim()==='maximize'.trim());
      minandmax = 1
    }
    var obj = {
      userid: +this.userid,
      minandmax: minandmax
    }
    if (this.userPreferences.length === 0)
      this.commonService.postuserpreference(obj).subscribe(res => {
        this.getuserPreferences();
        this.toastr.success('preference updated successfully');
      }, err => {
        this.toastr.error('error in geting ser preferences');

      })

    if (this.userPreferences.length === 1) {
      this.commonService.UpadateUserPreferences(obj, 'minandmaxupdate').subscribe(res => {
        this.getuserPreferences();
        this.toastr.success('preference updated successfully');
      }, err => {
        this.toastr.error('error in geting ser preferences');

      })
    }

  }

  show_pendinglotd(){

    this.router.navigate(['/logout']);
  /*   this.logoutservice.GetUsersPendinginfo(this.userid).subscribe(res => {
      if (res.status === 200) {
        console.log(JSON.parse(res.body[0])[0].assignlot);
        console.log(JSON.parse(res.body[0])[0].pendinglot);
        this.pendinglot=JSON.parse(res.body[0])[0].pendinglot;
        this.assignlot=JSON.parse(res.body[0])[0].assignlot;
        this.pendinglotinfoModalRef = this.modalService.show(this.pendinglotinfoTemplate, this.config);
        const aa = document.getElementsByClassName("modal-content");
        aa[0].classList.remove("modal-content");
      }
    }, err => {
      this.toastr.error('Error while geting user info');
    }); */

  }
  closeppop(){
    if (this.pendinglotinfoModalRef) {
      this.pendinglotinfoModalRef.hide();
    }
    this.logoutservice.PendingLotInfo(this.userid).subscribe(res => {
      if (res.status === 200) {
        this.router.navigate(['/logout']);
      }
    });
  }
}
