import { Component, OnInit, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'bb-custom-card-panel',
  template: `
    <div *ngIf = "sendCardObj">
        <bb-custom-card [ngClass]="(card_col_css == 'custom') ?  cards['CARD_COL_CSS'] :  card_col_css "
        [chartConfig] = "component"
        [cards]= _cards 
        [template]="_template" 
        [isSelection]="isSelection" 
        (onSelect)="onSelect($event)"
        (onPerformAction)="performAction($event) ">
        </bb-custom-card>
    </div>
    <div *ngIf = "!sendCardObj" [ngClass]="'CONTAINER_'+_template">
      <div class="header-title-panel" *ngIf="headerTitle" >{{ headerTitle }}</div>
      <div class="title-panel" *ngIf="title && !headerTitle" (click)="onTitleClicked($event)">
        <div>{{title}}</div>
        <div class="css-arrow" [ngClass]='{"collapse": !expand}'></div>
      </div>
      <div *ngIf= "empInfo" class="multiple-chart-header" >
        <div class = "multiple-chart-icon" style="background-color:#c8bdb6;">
            <img *ngIf="imageNotFound == false" [src]="imageSrc" (error)=" setImageNotFound(true)"/>
            <span class="multiple-chart-header-icon" *ngIf="imageNotFound == true" style = "color: white;">{{tabContentInitials}}</span>
        </div>
        <div>
            <div *ngIf= "empInfo"class="simple-card-date" style="color:#000000;text-transform:uppercase;"><b style="color:#000000;">{{ empName }}</b> ({{ empDesignation }}), <img src="dashboard/assets/images/svg/pin_small.svg"> {{ empHQ }}</div>
            <div *ngIf= "lastDCRDate" class="simple-card-date">Last Confirmed DCR Date: {{ lastDCRDate }} </div>
        </div>
      </div>
      <div *ngIf="expand" [ngClass]="'CONTENT_'+_template">
        <bb-custom-card *ngFor= "let card of _cards" [ngClass]="(card_col_css == 'custom') ?  card['CARD_COL_CSS'] :  card_col_css " 
        [card]= "card" 
        [template]="_template" 
        [isSelection]="isSelection" 
        (onSelect)="onSelect($event)"
        (onPerformAction)="performAction($event) ">
        </bb-custom-card>
      </div>
    </div>
  `,
  styles: [`

  .simple-card-date {
    font-size: 14px;
    font-weight: 400;
    color: #787878;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-left: 5px;
  }

  .multiple-chart-header {
    display: flex;
    padding: 8px;
    align-items: center;
  }

  .multiple-chart-icon {
    height: 32px;
    width: 32px;
    background-color: #c8bdb6;
    border-radius: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title-panel {
    position: relative;
    cursor: pointer;
    padding: 8px 8px 0 8px;
  }
  
  .header-title-panel{
    position: relative;
    padding: 8px 8px 0 8px;
  }

   div[class^="CONTAINER_SIMPLE_CARD"],
   div[class^="CONTAINER_CUSTOM_CHART"],
   div[class^="CONTAINER_PROFILE_CARD"]{
    margin: 0;
    padding: 8px 0;
    display: block;
    float: left;
    width: 100%;
    border-bottom: 1px solid rgb(220, 220, 220);
  }

  .default-content,
  div[class^="CONTENT_PROFILE_CARD"]{
    display: flex;
    padding: 8px 0;
    margin: 0;
    flex-direction: row;
    overflow: auto hidden;
    position: relative;
    width: calc( 100% - 8px );
  }

  div[class^="CONTENT_SIMPLE_CARD"],
  div[class^="CONTENT_CUSTOM_CHART"]{
    margin: 0;
    padding: 0;
    width: 100%;
    height: auto;

    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

	
   div[class^="CONTAINER_SIMPLE_CARD_5"],
   div[class^="CONTAINER_SIMPLE_CARD_4"]{
    margin: 0;
    padding: 10px;
    display: block;
    float: left;
    width: calc(100% - 20px);
    border-bottom: 1px solid rgb(220, 220, 220);
  }


  div[class^="CONTENT_SIMPLE_CARD_5"],
  div[class^="CONTENT_SIMPLE_CARD_4"]{
    margin: 0;
    padding: 0;
    width: 100%;
    height: auto;

    display: flex;
    flex-direction: row;
    flex-wrap: initial;
    
  }

  .css-arrow {
    height: 6px;
    width: 6px;
    border-width: 1px;
    border-style: solid;
    border-color: #666 #666 transparent transparent;
    position: absolute;
    right: 16px;
    top: calc(50% - 5px);
    transform: rotate(135deg);
    transition: transform 200ms;
  }

  .css-arrow.collapse {
    transform: rotate(45deg);
  }


  @media (min-width:320px) {
       div[class^="CONTENT_SIMPLE_CARD"] bb-custom-card,
       div[class^="CONTENT_CUSTOM_CHART"] bb-custom-card {
           width: 100%;
       }

		.card-col-8{
			width: 50% !important;
		}
		.card-col-2
		{
        	width: 50% !important;
       	}
   }



   @media screen and  (min-width:320px) and (max-width:480px) {
       
       div[class^="CONTENT_SIMPLE_CARD_RANKING"] bb-custom-card {
           width: 50%;
       }

		.card-col-8{
			width: 50% !important;
		}
		.card-col-2
		{
        	width: 50% !important;
       	}
   }

   @media (min-width:576px) {
       div[class^="CONTENT_SIMPLE_CARD"] bb-custom-card,
       div[class^="CONTENT_CUSTOM_CHART"] bb-custom-card {
           width: 50%;
       }
		.card-col-2
		{
        	width: 50% !important;
	     }
   }

   @media (min-width:768px) {
       div[class^="CONTENT_SIMPLE_CARD"] bb-custom-card,
       div[class^="CONTENT_CUSTOM_CHART"] bb-custom-card {
           width: 33.33%;
       }
       
       .card-col-2{
         width: 50% !important;
       }

       .card-col-6{
         width: 16.66% !important;
   }
	.card-col-8{
	         width: 12.50% !important;
	   }
   }

   
  @media screen and  (min-width:480px) and (max-width:768px) {
       
       div[class^="CONTENT_SIMPLE_CARD_RANKING"] bb-custom-card {
           width: 33.33% !important;
       }

       
       div[class^="CONTENT_SIMPLE_CARD_RANKING"] .card-col-6 {
           width: 33.33% !important;
       }

       div[class^="CONTENT_SIMPLE_CARD_RANKING"] .card-col-8 {
           width: 16.66% !important;
       }
		.card-col-2
		{
        	width: 50% !important;
       	}
   }


   @media (min-width:992px) {
       div[class^="CONTENT_SIMPLE_CARD"] bb-custom-card,
       div[class^="CONTENT_CUSTOM_CHART"] bb-custom-card {
           width: 25%;
       }

	   .card-col-2{
         width: 50% !important;
       }
       .card-col-3{
         width: 33.33% !important;
       }
       .card-col-6{
         width: 16.66% !important;
       }
		.card-col-8{
		      width: 12.50% !important;
		}
   }

   @media (min-width:1200px) {
       div[class^="CONTENT_SIMPLE_CARD"] bb-custom-card,
       div[class^="CONTENT_CUSTOM_CHART"] bb-custom-card {
           width: 25%;
       }

       .card-col-3{
         width: 33.33% !important;
       }
       .card-col-6{
         width: 16.66% !important;
       }
		.card-col-8{
		      width: 12.50% !important;
		}
		.card-col-2
		{
        	width: 50% !important;
       	}
   }
  `],
  encapsulation: ViewEncapsulation.None
})
export class BBCustomCardPanel implements OnInit {

  constructor() { }

  @Input() title: any;
  @Input() cards: any;
  @Input() component: any;
  @Input() isSelection = false;
  @Input() _template = 'default';
  @Input() parentData: any;

  @Output() onDrillDown: EventEmitter<any> = new EventEmitter();
  @Output() onPerformAction: EventEmitter<any> = new EventEmitter();
  
  _cards: any = [];
  headerTitle = '';
  card_col_css = 'card-col-4';
  expand: boolean = true;
  sendCardObj: boolean = false; //added by SonamK
  lastDCRDate: any;
  empInfo: any;
  empName: any;
  empDesignation: any;
  empHQ: any;
  empDet: any[] = [];
  imageSrc: any;
  tabContentInitials: any = '';
  ngOnInit() {
    console.log('BBCustomCardPanel ngOnInit :: cards', this.cards, this.component);
	//added by Sonam K
     console.log(localStorage.getItem('DrildropdownDoctorClick'));
     localStorage.removeItem('DrildropdownDoctorClick');
    if ( this.component['chartConfig'] ) {
      this.sendCardObj = true;
    }
	//added by Sonam K
    if( this.component['dcr_date_info']) {
        if ( this.cards[0]  && this.cards[0]['LAST_DCR_DATE'] ) {
            this.lastDCRDate = this.cards[0]['LAST_DCR_DATE'];
            console.log('this.lastDCRDate >>', this.lastDCRDate);
        }
    }
    if( this.component['emp_info']) {
        if ( this.cards[0]  && this.cards[0]['EMP_DETAIL'] ) {
            this.empInfo = this.cards[0]['EMP_DETAIL'];           
            console.log('this.EMP_DETAIL >>', this.empInfo);
            this.empDet = this.empInfo.split("~~");
            this.empName = this.empDet[0];
            this.empDesignation = this.empDet[1];
            this.empHQ = this.empDet[2];
            console.log('this.empDet >>', this.empDet);     
        }  
    }
    if( this.empName && this.empName.length > 0 ) 
    {
        var initials = this.empName.match(/\b\w/g) || [];
        this.tabContentInitials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
    }      
    console.log('tabContentInitials  >>', this.tabContentInitials); 
    
    console.log('BBCustomCardPanel ngOnInit :: parentData', this.parentData);
    this._cards = Object.assign([], this.cards);
    this.preProcessComponent();
    var firstCard: any = this._cards[0];

	//Changes for Sells Planning Summary - Start 
    if( firstCard && firstCard.copykeys && this.parentData && this.parentData !== undefined)
    {
        var copyKeysDataArr = firstCard.copykeys.split(',');
        copyKeysDataArr.map( (key: any) => {
            var value = this.parentData[key];
            if( value )
            {
                this._cards[0][key] = this.parentData[key];
            }
        });
    	if( this._cards[0] && this._cards[0]['_OBJECT_KEY'] )
    	{
        	var objectKey = this._cards[0]['_OBJECT_KEY'];
        	var storageKey = this._cards[0]['_STORAGE_KEY'];
      var storageValue = localStorage.getItem(storageKey) + '';
      console.log('storageValue 1... ',this._cards[0], storageValue);
			if(storageValue === 'null')
			{
				storageValue = this._cards[0][storageKey];
				console.log('storageValue 2... ', storageValue);
			}
			storageValue = storageValue.padEnd(10)// Temporary padding Space 
			console.log('objectKey ',objectKey, storageKey, storageValue);
        	this._cards[0][objectKey] = storageValue;
      }
      
    }
  //Changes for Sells Planning Summary - End
  	// This is for Setting parentData _OBJECT_Key
	if( this.parentData && this.parentData['_OBJECT_KEY'] )
	{
    	var objectKey = this.parentData['_OBJECT_KEY'];
		var storageValue = this.parentData[objectKey] + '';
		console.log('storageValue 1... ',this.parentData, objectKey, storageValue);
		if(storageValue !== 'null')
		{
		  this._cards = this._cards.map((crd: any) => {
	          if( crd )
	          {
	          	crd[objectKey] = storageValue;
	          }
	          return crd;
	      });
	      console.log('storageValue 2... ',JSON.stringify(this._cards));
		}
	}
     console.log('BBCustomCardPanel ngOnInit ::  firstCard', firstCard);
    if( this.parentData == undefined ||  this.parentData !== undefined)
    {
        console.log('BBCustomCardPanel firstCard is not null');
    if( firstCard['IS_SUMMARY'] && this._cards.length > 1 )
    {
        firstCard = this._cards[1]; //Advanced to 2nd Card in case 1st Card is Summary Card
    }
    if( firstCard && firstCard['header_column'] )
    {
        this.headerTitle = firstCard[firstCard['header_column']] || firstCard['header_column'] || '';
        console.log('BBCustomCardPanel ngOnInit :: headerTitle ', this.headerTitle);
        if(this.headerTitle.includes('<')){
            var temp  =this.headerTitle.substring(
                    this.headerTitle.lastIndexOf("<") + 1, 
                    this.headerTitle.lastIndexOf(">")
                );
            //console.log('headerTitle1 ',temp, this.parentData[temp]);
            var tempValue=this.parentData[temp] ;
            this.headerTitle=this.headerTitle.replace("<"+temp+">", tempValue);
            //console.log('headerTitle 2',this.headerTitle, this._cards[0]['title']);
            
            var tempTitle= this._cards[0]['title'].replace("<"+temp+">", tempValue);
            //console.log('headerTitle tempTitle',tempTitle);
            this._cards[0]['title']=tempTitle;
        }
    }
  }
  }

  preProcessComponent() {
    if(this.component){
      this._template = this.component.component_type;
      this._cards = this._cards.map((c: any) => {
          if( this.component.chart_properties )
          {
            c['chartType'] = this.component.chart_properties.chartType;
            c['labels'] = this.component.chart_properties.labels;
            c['options'] = this.component.chart_properties.options;
          }
          return c;
      });

      if(this.component.card_col_css)
      {
        this.card_col_css = this.component.card_col_css;
      }
    }
  }

  onSelect(card: any)
  {
    this._cards = this._cards.map((c: any) => {
      if( c === card)
      {
        c['selected'] = true;
      }
      else
      {
        c['selected'] = false;
      }
          
      
      console.log("onSelect of card after End ", c);
      return c;
    });
    
    this.onDrillDown.emit(card);
  }
 
  // Added by Pravin K on 18-MAR-20 [To add-task popup]  START	  
  performAction(link: any)
  {
      console.log("BBCustomCardPanel performAction", link);
      this.onPerformAction.emit(link);
  }
  // Added by Pravin K on 18-MAR-20 [To add-task popup]  END
 
  onTitleClicked(event: any) {
    event.preventDefault();

    this.expand = !this.expand;
  }
  imageNotFound = false;

  setImageNotFound( imagePresent: any ) {
      console.log( 'imagePresent >>', imagePresent);
      this.imageNotFound = true;
  }


}
