import { Component, OnInit, OnChanges  , ViewChild, TemplateRef, HostListener,ViewContainerRef, ElementRef, Input, Output, EventEmitter,ViewEncapsulation ,Pipe, Renderer2, ChangeDetectorRef} from '@angular/core';
import { SlicePipe } from '@angular/common';

import { ContentService } from '../shared/services/content.service';
import { ContentsSandbox } from '../shared/sandbox';
import { GroupByPipe } from '../shared/pipes/group-by.pipe';
import { OrderbyDataPipe } from '../shared/pipes/orderby-data.pipe';
import { FilterByPipe } from '../shared/pipes/filter-by.pipe';

declare var previewMultipleDocuments: any;
declare var openSharePlugin: any;
export enum KEY_CODE {
    ESCAPE = 27,
}

@Component( {
    selector: 'content-header',
    templateUrl: './content-header.component.html',
    styleUrls: ['./content-header.component.css'],
    //encapsulation: ViewEncapsulation.None,
    providers : [GroupByPipe ,OrderbyDataPipe]
})
export class ContentHeaderComponent implements OnInit {

    isSearchHeader: any;
    selected: any;
    searchText: any;   
    //Categorised Data
    @Input()docReferences: any;
    //@Input() refSerList;
    @Input() references: any;
    @Output() onSearch: EventEmitter<any> = new EventEmitter<any>();
    @ViewChild('myInput') myInput: ElementRef | any;
    @ViewChild('selectOpt') selectOpt: any;
    @ViewChild('allOpt') allOpt: any;
    
    themeColor = "#00caff";
    chipColor = "1px solid"+this.themeColor;
    
    ASSET_IMG_URL = "dashboard/assets/images";
    
    //groupByView;
    selectedList: Array<any> = [];
    selectedOption: string | any;
    groupByView = 'documentMenu';  
  //  column: string = 'key';
    direction: number | any;
    isDesc: boolean = false;
   // selectedRefSer:Array<any> = [];
    selectedRefSer : any[]=[];
    color: 'accent' | any;
    selectedChipList: any[] = [] ;
    refSerArray: any[] =[];
    hostUrl: any;
    docTypeList: any[] = [];
    fileTypeList: any[] = []; 
    fisrtArray: any[] = [];
    secondArray: any[] =[];
    default_obj_links: any[]=[];
    pinLink: any;
    showPinnedContents = false;
    groupByLink: any;
    isDefaultGroupBy = true;
    tagArray: any =[];
    searchVal: any;
    searchChips: any=[];
   
    constructor( private contentService:ContentService ,private groupByPipe :GroupByPipe , private orderbyDataPipe :OrderbyDataPipe, private renderer: Renderer2, private contentsSandbox: ContentsSandbox, public changeDetectorRef: ChangeDetectorRef) {
    
    
    }

    ngOnInit() {

        // fOR MULTIPLE CONTENTS
        /*        this.contentService.onSelectContent.subscribe(
                selectedList => {
                    this.selectedList = selectedList;
                }
        );*/
        
        this.hostUrl = this.contentsSandbox.getHostUrl();
        if(!this.hostUrl){
            this.ASSET_IMG_URL = "/ibase/E12BROWSER/"+this.ASSET_IMG_URL;
        }

        this.pinLink={ 
                FieldName: "line_no",
                FormNo: "1",
                LineNo: "",
                LinkArg: "",
                LinkForm: "",
                LinkTitle: "Show Pinned",
                LinkType: "CL",
                RightsChar: "S",
                TargetObject: "",
                Image: "visioniconpin-active",
                handler:this.showPinned.bind(this)
            };
            
         this.groupByLink={ 
                FieldName: "line_no",
                FormNo: "1",
                LineNo: "",
                LinkArg: "",
                LinkForm: "",
                LinkTitle: "Group By Association",
                LinkType: "CL",
                RightsChar: "S",
                TargetObject: "",
                Image: "visioniconfilter",
                handler:this.changeGroupView.bind(this)
            };   
        
        this.default_obj_links=
            [{ 
                FieldName: "line_no",
                FormNo: "1",
                LineNo: "",
                LinkArg: "",
                LinkForm: "",
                LinkTitle: "Search",
                LinkType: "CL",
                RightsChar: "S",
                TargetObject: "",
                Image: "visioniconsearch",
                handler:this.showSearch.bind(this)
            },
                { 
                    FieldName: "line_no",
                    FormNo: "1",
                    LineNo: "",
                    LinkArg: "",
                    LinkForm: "",
                    LinkTitle: "Recently Used",
                    LinkType: "CL",
                    RightsChar: "S",
                    TargetObject: "",
                    Image: "visioniconsort",
                    handler:this.sortByRecent.bind(this)
            },
                { 
                    FieldName: "line_no",
                    FormNo: "1",
                    LineNo: "",
                    LinkArg: "",
                    LinkForm: "",
                    LinkTitle: "Fequently Used",
                    LinkType: "CL",
                    RightsChar: "S",
                    TargetObject: "",
                    Image:"visioniconsort",
                    handler:this.sortByFrequent.bind(this)
            }
            ];
        
            this.default_obj_links.push(this.pinLink);
            this.default_obj_links.push(this.groupByLink);

            console.log(' default_obj_links ',this.default_obj_links );
            console.log('docReferences --> ' , this.docReferences);
            this.collectTagValue(this.docReferences);
            this.contentsSandbox.onLinksCreation.emit(this.default_obj_links);
    }

   
    changeFilter(refSer: any, checked: any){
        //console.log('$$$ filter value $$['+refSer+']---'+checked);
        this.contentService.refSerChange(refSer);
    }

    sortBy(value: any) // for recently used and Frequently used
    {
        this.contentService.sortContentBy(value);
    }
    sortByRecent()
    {
        this.contentService.sortContentBy('recent');
    }
    sortByFrequent() 
    {
        this.contentService.sortContentBy('frequent');
    }

    onEnter(searchValue: any){
      //console.log("<========= enter event occured on search =========>", searchValue);
      //this.contentService.searchContentBy(searchValue);
      this.onSearch.emit(searchValue);
      this.addSearchCip(searchValue);
    }
    
    viewDocument(){
        
        let selectedArray: Array<any> = [];
        this.selectedList.forEach(
                content => {
                    selectedArray.push(
                    {
                        ID: content.docId,
                        NAME: content.docType
                    }
                    );
                }
        );
        
        previewMultipleDocuments(selectedArray);
    }
    
    shareContents(){
        let selectedArray: Array<any> = [];
        this.selectedList.forEach(
            content => {
                selectedArray.push(
                {
                    ID: content.docId,
                    NAME: content.docName
                }
                );
            }
        );
    
        openSharePlugin('',selectedArray);
    }
    
   
      
      select(refser: any)
      {
         // this.selectedRefSer.push(refser);
          //console.log("selectedRefSer ::",this.selectedRefSer);
      }
      
      ngOnChanges()
      {

          
      }
        showSearch() {
          this.isSearchHeader=true;
          console.log('showSearch ',this.isSearchHeader);
          setTimeout(
              () => {
                  this.renderer.selectRootElement(this.myInput.nativeElement).focus();
              }, 500);
      }
      
      onCancel(){
          this.onSearch.emit('');
          this.searchVal = '';
          this.searchChips = [];
      }
      
      @HostListener( 'window:keyup', ['$event'] )
      keyEvent( event: KeyboardEvent ) {
          if ( event.keyCode === KEY_CODE.ESCAPE ) {
              console.log('key escape ');
              this.onSearch.emit('');
              this.myInput.nativeElement.value = '';
              this.isSearchHeader = false;
              this.searchVal = '';
              this.searchChips = [];
          }
      }

      
     removeFromList(selected: any)
      {
        //console.log("removeFromList ",selected);
        this.selectedChipList = this.selectedChipList.filter(
                                (opt: any) => {
                                    return opt !== selected;
                                }
                              );
        this.contentService.sortByRefSer(this.selectedChipList);
        
      }
      
     deselect(){
         //console.log('this.selectedChipList before',this.selectedChipList);
         
         if(this.selectedChipList.length > 1)
         {
             //console.log('NOT EXIST ALL',this.selectedChipList);
             this.selectedChipList = ['ALL'];
          }
         this.contentService.sortByRefSer(this.selectedChipList);
        // console.log('this.selectedChipList after',this.selectedChipList);
     }

     optSelected(refSer: any){
         //console.log('option selected',this.selectedChipList);
         if(this.selectedChipList.length > 2 && !this.selectedChipList.includes('ALL'))
         {
             this.selectedChipList = this.selectedChipList.filter(
                                         (opt: any) => {
                                             return opt !== refSer;
                                         }
                                      );
             console.log('---this.selectOpt------',this.selectedChipList);
             this.selectOpt.close();
             alert("Cannot select more than two");
         }
         if(this.selectedChipList.includes('ALL'))
         {
             //console.log("allOpt  in include :::",this.allOpt);
             this.selectedChipList = this.selectedChipList.filter(
                     (opt: any) => {
                         return opt !== 'ALL';
                     }
                   );
         }
         this.contentService.sortByRefSer(this.selectedChipList);
     }
     
     getRefSerDesc(refSer: any){
         if(refSer == "ALL")
         {
             return refSer.toLowerCase();;
         }
         else
         {
           let refSerDetail = this.references.find((x: any) => x.refSer === refSer);
           return refSerDetail.refSerDescr.toLowerCase();;
         }
     }
     
     
     showPinned()
     {
         this.showPinnedContents=!this.showPinnedContents;
         this.contentService.toggleHeaderPinned(this.showPinnedContents);
         this.default_obj_links[3].LinkTitle = this.showPinnedContents ? 'Show All' : 'Show Pinned';
         this.default_obj_links[3].Image = this.showPinnedContents ? 'visioniconpin-active' : 'visioniconpin-inactive';
         this.contentsSandbox.onLinksCreation.emit(this.default_obj_links);
     }
    
     changeGroupView()
     {
         this.isDefaultGroupBy=!this.isDefaultGroupBy;
         this.default_obj_links[4].LinkTitle = this.isDefaultGroupBy ? 'Group By Association' : 'Group By Document Type';
         var groupBy = this.isDefaultGroupBy ? 'docContent' : 'association';
         this.contentService.onGroupByChange.emit(groupBy);
         this.contentsSandbox.onLinksCreation.emit(this.default_obj_links);
     }
     
     setValue(value: any){
         console.log("setVlaue -- >" , value);
         this.onSearch.emit(value);
         this.searchChips = [];
         this.searchChips.push(value.trim());
         this.searchVal = '';
       }
     
     collectTagValue(content: any){
         var tagValue;
         for( var i = 0; i < content.length; i++ )
         {
           //console.log("each --> " ,  this.products[i]["descr"]);
           if(content[i]["descr"])
           {
              tagValue = this.getTagStartWithHash(content[i]["descr"]);
              console.log("tagValue --> " ,  tagValue);
              this.getSplittedTagValue(tagValue);  
           }
          }
     }
     
     getTagStartWithHash(str: any)
     {
       console.log("str --> " ,  str);
       if(str && str.includes("#")){
       return  str.match(/(^|\s)\#(\w+)/g).map((v: any) => {
               return ("#" + v.trim().substring(1));
           });
       }
     }

     getSplittedTagValue(tagValue: any)
     {
        console.log("getSplittedValue --> " ,  tagValue);
        var i;
        if(tagValue)
        {
             for(i = 0; i < tagValue.length; i++)
             {
                console.log(" --> " ,  tagValue[i]);
                if(this.tagArray.indexOf(tagValue[i]) === -1)
                {
                    this.tagArray.push(tagValue[i])
                }            
             }
             console.log("tagArray --> " ,  this.tagArray);
        }

     }
     
  addSearchCip(value: any): void {
       
        if ((value || '').trim()) {
          this.searchChips = [];
          this.searchChips.push(value.trim());
          this.searchVal = '';
        }
  }

  removeSearchCip(value: any): void {
    const index = this.searchChips.indexOf(value);
    if (index >= 0) {
      this.searchChips.splice(index, 1);
      this.onSearch.emit('');
      this.searchVal = '';
    }
  }
}
