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

import { ContentsSandbox } from '../shared/sandbox/content.sandbox';

import { Router } from '@angular/router';

@Component({
  selector: 'content-assoc-objects',
  templateUrl: './content-assoc-objects.component.html',
  styleUrls: ['./content-assoc-objects.component.css']
})
export class ContentAssocObjectsComponent implements OnInit {

  @Input() content: any;
  @Output() onClose: EventEmitter<any> = new EventEmitter<any>();
  @Output() onSelect: EventEmitter<any> = new EventEmitter<any>();

  status = "loading";
  objList: any[] = [];
  filetype_icon_url: any;
  objIconUrl = "/ibase/images/menuImages/mob/"
  hostUrl: any;
  ASSET_IMG_URL = "dashboard/assets/images/svg";
  storedTransKey:any ; // Added by Pravin K on 17-APR-19 [ To store associate object list in session storage]

  constructor(public contentSandbox: ContentsSandbox, private router: Router, public zone:NgZone) {
    // Added by Pravin K on 09-OCT-18 [for the issue of new added transaction] START
    let that = this;
    setTimeout(function() {
        that.zone.run(() => {
            console.log('.view refreshed constructor..');
        });
    }, 1);
    // Added by Pravin K on 09-OCT-18 [for the issue of new added transaction] END
  }

  ngOnInit() {
      this.content = this.contentSandbox.getSelectedContent();
      this.setIconUrl();
      this.hostUrl = this.contentSandbox.getHostUrl();
      console.log("Content Details in content-assoc-objects",this.content);

      // Added by Pravin K on 17-APR-19 [ To store associate objects in session storage] START
      this.storedTransKey = "assocObjList_"+this.content.docId
      var storedAssocObjs = this.contentSandbox.getSessionStorageItem( this.storedTransKey );
      console.log("Associate object storedAssocObjs : ",storedAssocObjs);

      if(storedAssocObjs){
          var resp = JSON.parse(storedAssocObjs);
          if (  typeof resp === 'string' )
          {
            resp = JSON.parse(resp);
          }
          console.log("storedAssocObjs resp : ",resp);
          this.objList = resp.assocObjList;
          if(this.objList.length == 0){
              this.status = "nodata";
          }
          /*Added by SOnam K on 30-JUL-19 [single object in associating files  should get selected by default] START*/
          else if(this.objList.length == 1) {
          	this.selectObject(this.objList[0]);
          }
         /*Added by SOnam K on 30-JUL-19 [single object in associating files  should get selected by default] END*/
          else {
              this.status = "loaded";
          }
      }
      else
      {
        this.contentSandbox.getAssocObjList(this.content.docType, this.content.docId,
          (resp: any) => {
              console.log("Response in ContentAssocObjectsComponent",resp);
              if(resp.result == "success"){
                  // Added by Pravin K on 17-APR-19 [ To store associate objects in session storage] START
                  //Commented by Sonam K on 30-JUL-19 [To not store data in session storage]
                 // this.contentSandbox.setSessionStorageItem(this.storedTransKey,JSON.stringify(resp));
                  // Added by Pravin K on 17-APR-19 [ To store associate objects in session storage] END

                  this.objList = resp.assocObjList;
                 //Added by Sonam K on 06-Sept-19 [ To resolve back button issue of assoc object ]
                  this.contentSandbox.assocObjList = this.objList;

                  /*Added by Sonam K on 30-JUL-19 [single object in associating files  should get selected by default]*/
                  if(this.objList.length == 1) {
                      this.selectObject(this.objList[0]);
                  }

                  if(this.objList.length == 0){
                      this.status = "nodata";
                  } else {
                      this.status = "loaded";
                  }
              }else if(resp.result == "failure"){
                  this.status = "failed";
              }
          }
        );
      }
      // Added by Pravin K on 17-APR-19 [ To store associate objects in session storage] END
  }

  close(){
      //this.onClose.emit();
      this.contentSandbox.onAssocOption.emit(false);
  }

  setIconUrl() {
      if ( ['png', 'jpg', 'jpeg', 'gif'].indexOf( this.content.fileType.toLowerCase() ) >= 0 ) {
          this.filetype_icon_url = this.ASSET_IMG_URL + '/image.svg';
      } else if(['mp4', 'avi', 'flv', 'swf' , 'mpg', 'mpeg', 'mkv'].indexOf( this.content.fileType.toLowerCase() ) >= 0){
          this.filetype_icon_url = this.ASSET_IMG_URL + '/video.svg';
      } else {
          this.filetype_icon_url = this.ASSET_IMG_URL + '/'+ this.content.fileType.toLowerCase() + '.svg';
      }
  }

  selectObject(object: any)
  {
    this.contentSandbox.cleareSelectedTranObjects();
    this.contentSandbox.setSelectedAssocObject(object);

    this.router.navigateByUrl('assocTransactions', { skipLocationChange: true });
  }

	onError(imageElement: any, description: any) {
        var targetImg = imageElement.target;
		var hostURL: string = this.contentSandbox.getHostUrl();
		var errorSrc: string = hostURL + '/ibase/CustomMenuImageServlet?fldValue=' + description + '&object=&objName=&ALT_FLD_VALUE=' + description + '&isOval=true';
		targetImg.src = errorSrc;
	}

}
