import { Component, OnInit, Inject } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MD_DIALOG_DATA, MdDialogRef } from '@angular/material';
import { BsDatepickerConfig } from 'ngx-bootstrap';

@Component({
  selector: 'app-point-share',
  templateUrl: './point-share.component.html',
  styleUrls: ['./point-share.component.scss']
})
export class PointShareComponent implements OnInit {
  pointShareCount:number =0 ;
  perunitprice:number =0; 
  errmsg:any;
  useridd: any;
  colorTheme = 'theme-dark-blue';
  totalAmount:number=0 ;
  allocatedPoint :number = 0;  
  availablePoint:number = 0 ;
  bsConfig: Partial<BsDatepickerConfig>;
  superAdmin: any;
  custtype: any;
  pointId: any;
  constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService,public dialogRef: MdDialogRef<PointShareComponent>,
    @Inject(MD_DIALOG_DATA) public data: any) { 
      this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' }, { containerClass: this.colorTheme });
    }

  ngOnInit() {  
    console.log({'data' : this.data});
    if((this.data.userInfo.point_Allocated)){
      this.allocatedPoint  = this.data.userInfo.point_Allocated ;
    }
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    console.log({'this.superAdmin':this.superAdmin,'this.custtype': this.custtype});
    // debugger;
    // if(this.superAdmin === true){
    //   this.pointId = this.useridd ;
    // }

    // if(this.custtype === true){
    //   this.pointId = this.useridd ;
    // }
 
    console.log(this.allocatedPoint);
  
    this.checkAvailablePoint()
  }
  errFlag:boolean=false;
  SharePoint(){
    var that = this; 
    // if(this.pointShareCount > this.availablePoint){
  
    // }
    // else{
      if((this.pointShareCount == undefined)||(this.payment_stauts == undefined)){
        this.errFlag = true;
        this.errmsg = "All Fields are mendatory";
        var err = setTimeout(function(){
            that.errFlag = false; 
            clearTimeout(err);
        },5000)
          return;

      }else{

        var insertPoint = {
          by: this.useridd,
          to: this.data.userInfo._id,
          points: this.pointShareCount,
          rate: this.perunitprice,
          totalAmount:this.totalAmount,
          Payment_type: this.payment_stauts,
          created_date: new Date().toISOString(),
      }

      if(this.creditF === true){
        insertPoint['credit_date'] = this.credit_date;
      }

      if(this.paidF === true){
        insertPoint['remarks'] = this.remarks;
      }


     this.contactService.getAvialblePoints(this.useridd,this.pointShareCount).subscribe(res=>{
       console.log(res);
       if (res.available_points < this.pointShareCount) {
         this.errFlag = true;
         this.errmsg = "Insufficient Points";
         var err = setTimeout(function () {
           that.errFlag = false;
           clearTimeout(err);
         }, 5000)
         return;

       }else{
         this.contactService.addPoints(insertPoint).subscribe(res=>{
         console.log(res);
         this.dialogRef.close('added')
       })

       }
      //  console.log({'insertPoint':insertPoint});      
     })
    
      }

  }
  closebox(){
    this.dialogRef.close('cancel');
  }

  checkAvailablePoint(){
    console.log
    var distId = this.data.userInfo._id;
    console.log({'distId':distId});
    var distPoint = '0' ;
    this.contactService.getAvialblePoints(distId,distPoint).subscribe(res=>{
      // console.log('res=>',res.json());
      if((res.available_points == undefined)||(res.available_points < 0 )){
        this.availablePoint  = 0 ;
      }else{
        this.availablePoint = res.available_points?res.available_points:0 ; 
      }
     
    })
  }

  paymentStauts:any=["Paid","Credit","Send Payment Link"];
  payment_stauts:any;
  creditF:boolean = false;
  paidF:boolean=false;
  splF:boolean=false;
  remarks:any;
  credit_date=new Date();
  optionShow(poption){
    console.log("Inside function");
    console.log(poption);
    if(poption=='Paid'){this.creditF = false;this.paidF=true;this.splF=false;}
    if(poption == 'Credit'){this.paidF=false;this.splF=false;this.creditF = true;}
    if(poption == 'Send Payment Link'){this.splF=true;this.creditF = false;this.paidF=false;}
  }


  linkShare(iden){
    console.log(iden);
  } 

  calculateTotal(){
    this.totalAmount = this.pointShareCount * this.perunitprice ; 
  }
}
