import { Injectable, EventEmitter }             from "@angular/core";
import { Subscription }           from "rxjs";
import { ContentsApiClient }      from '../services/contentsApiClient.service';
// import { Observable }       from 'rxjs/Observable';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable }       from 'rxjs';
import { BehaviorSubject } from 'rxjs';


import { Content }                   from '../models';

declare var callDataModel: any;

@Injectable()
export class ContentsSandbox {

  //public contentList$ = this.appState$.select("contentList");
  public contentList$ = new BehaviorSubject<any>([]);
  public userRights$ = new BehaviorSubject<any>([]);
  public assocObjListResp$ = new BehaviorSubject<any>([]);
  public assocTranscListResp$ = new BehaviorSubject<any>([]);
  public updateDocTransPageInfo$ = new BehaviorSubject<any>([]);
  public selectedContent:any;
  public selectedAssocObject:any;

  public selectedTranObjects: any=[] ;// All selected transaction objects
  public selectedTranId:any ;// current selected transaction object
  public selectedTemplate:any ;// current selected transaction object

  public pageSelectionDetails:any; // to store selection and important pages details

  public pluginMetadata:any;
  public hostUrl;
  public contentData:any;
  actionList:any;
  userRights: any[] = [];
  assocObjList: any[] = []; //Added by Sonam K on 06-Sept-19 [ To resolve back button issue of assoc object ]
  onContentAttached: EventEmitter<any> = new EventEmitter();
  onAssocOption: EventEmitter<boolean> = new EventEmitter();
  onLinksCreation: EventEmitter<any> = new EventEmitter();
//Added by Saitej .D To Play video on click at content-library dashboard Start
  onFilePreview: EventEmitter<any> = new EventEmitter();
//Added by Saitej .D To Play video on click at content-library dashboard End

  contentConfig:any = {};

  constructor(
    public contentsApiClient: ContentsApiClient,

  ) {

      this.hostUrl = this.fetchHostURL();
  }

  /**
   * Loads contents from the server
   */
  public loadContentList(userId:any): void {

    var loadFromDM = this.loadContentsFromDM.bind(this);
    var loadFromServer = this.loadContentsFromServer.bind(this);

    callDataModel('content_library_dm', loadFromDM, loadFromServer );

  }

  /**
   * Update content
   */
  public updateContent(content:any): void {
  }
  /**
   * Delete content
   */
  public deleteContent(content:any): void {
  }

  public addContent(docId:any){
      this.contentsApiClient.getDocContent(docId).subscribe(
              (result:any) => {
                  this.contentData.userDocContents.push(result);
                  this.contentList$.next(this.contentData);
              }
      );
  }

  setPluginMetadata(data:any){
      this.pluginMetadata = data;
  }

  getPluginMetadata(){
      return this.pluginMetadata;
  }

  loadContentsFromDM(fileData:any) {
      //console.log('ContentsSandbox loadContentsFromDM :::', fileData);
      //this.appState$.dispatch(this.contentAction.loadContentList(fileData));

      //this.contentList$ = this.contentsApiClient.getContentList(fileData);


      this.contentsApiClient.getContentList(fileData).subscribe(

              (result:any) => {
                  console.log('result in sandbox',result);
                  //console.log('Observable Initiated ...');
                      this.contentData = result;
                      this.contentList$.next(this.contentData);
                  });

  }

  loadContentsFromServer() {
      var userId = 'DUMMY';
      //console.log('ContentsSandbox loadContentsFromServer :::', userId);
      //this.appState$.dispatch(this.contentAction.loadContentList(userId));

      //this.contentList$ = this.contentsApiClient.getContentList(userId);

      this.contentsApiClient.getContentList(userId).subscribe(

              (result:any) => {
                      console.log('result in sandbox',result);
                      //console.log('Observable Initiated ...');
                      this.contentData = result;
                      this.contentList$.next(this.contentData);
                  });
  }

  updateDate(docId:any){
      this.contentsApiClient.updateDates( docId );
  }

  updatePinned(docId:any , status:any){
      this.contentsApiClient.updatePinned(docId , status);
  }

  setUserRights(response:any)
  {
      console.log('inside set user rights',response);
      if(response.obj_actions){
          console.log('Inside content view  ',response.obj_actions);

              if(response.obj_actions)
              {
                  response.obj_actions.forEach(
                     (obj:any) => {
                         console.log('ACTIONS',obj);
                         if(obj.ACTIONS)
                         {
                             console.log('ACTIONS:::::',obj.ACTIONS);
                             this.actionList = obj.ACTIONS.action;
                             this.actionList.forEach(
                                    (right:any) =>{
                                        console.log("right  ===> " , right.right_char);
                                        this.userRights.push(right.right_char);
                                    }
                             )
                             console.log('action list',this.actionList);
                         }
                     }

                  )

              console.log("userRights IN CONTENT VIEW" ,this.userRights );
          }
      }
      //Added by kamal.P Start
      if(response.obj_name)
      {
          this.contentConfig['objName'] = response.obj_name;
      }
      if(response.title)
      {
          this.contentConfig['title'] = response.title;
      }
	 //Addded by kamal.P End
  }

  getHostUrl() : string {
      return this.hostUrl;
  }

  fetchHostURL(): string {
    //   let HOST_URL: string = '';
      let HOST_URL: any = '';


      HOST_URL = localStorage.getItem( 'HOST_URL' );
    //   HOST_URL = JSON.parse (localStorage.getItem('HOST_URL')||'{}');

      if ( !HOST_URL ) HOST_URL = '';

      console.log( 'fetchHostURL[', HOST_URL, ']' );
      return HOST_URL;
  }

  setReponse(response:any){
    /*
    this.contentsApiClient.getContentList(response).subscribe(

              result => {
                  console.log('result in sandbox',result);
                  //console.log('Observable Initiated ...');
                      this.contentData = result;
                      this.contentList$.next(this.contentData);
                  });
    */

              this.contentData = response;
              this.contentList$.next(this.contentData);
  }

  deactivateDocContent(docId:any){
      this.contentsApiClient.deactivateDocContent(docId).subscribe(

              (resp:any) => {
                  console.log("Response on deactivateDocContent",resp);
                  if(resp['result'] == 'success'){
                    this.emitOnContentAttached();
                  }
              }
      );
  }

  emitOnContentAttached(){
      this.onContentAttached.emit();
  }


  getAssocObjList(docType:any, docId:any, callback:any){
      this.contentsApiClient.getAssociateObjList(docType, docId).subscribe(
             ( result:any) => {
                  console.log("AssociateObjList In Sandbox",result);
                  callback(result);
                  //this.assocObjListResp$.next(result);
              }
      );
  }

  getAssocTranscList(docType:any, docId:any, refSer:any, obj_name:any, table_name:any , trand_id_col:any, callback:any) {
       this.contentsApiClient.getAssocTransList(docType, docId, refSer, obj_name, table_name , trand_id_col).subscribe(
            (result:any) => {
                console.log("getAssocTranscList In Sandbox",result);
                callback(result);
                //this.assocTranscListResp$.next(result);
            }
        );
  }

  /* Added by Pravin K on 25-SEP-18 [to get getObjLinksDetails ] START */
  getObjLinksDetails(objName:any,targetObjName:any, callback:any) {
      this.contentsApiClient.getObjLinksDetails(objName,targetObjName).subscribe(
          (result:any) => {
              console.log("getObjLinksDetails In Sandbox",result);
              callback(result);
              //this.assocTranscListResp$.next(result);
            }
        );
    }
    /* Added by Pravin K on 25-SEP-18 [to get getObjLinksDetails ] START */

  updateDocTransPageInfo( transList :object , callback:any)
  {
    console.log("... updateDocTransPageInfo In Sandbox",transList);
    this.contentsApiClient.updateDocTransPageInfo( transList ).subscribe(
       ( result:any )=> {
            console.log("updateDocTransPageInfo In Sandbox",result);
            callback(result);
        }
    );
  }

  setSelectedContent(content:any){
      this.selectedContent = content;
  }

  getSelectedContent(){
      return this.selectedContent;
  }

  setSelectedAssocObject(content:any){
      this.selectedAssocObject = content;
  }

  getSelectedAssocObject(){
      return this.selectedAssocObject;
  }

  setSelectedTranId(selectedId:any){
    this.selectedTranId = selectedId;
  }

  getSelectedTranId(){
    return this.selectedTranId;
  }

  updateSelectedTranObjects( selectedTemplate:any, selectedPages:any, selectedPagesSeq:any, importantPagesSeq:any )
  {
    var selectedTranObj:any = this.getSelectedTranObjectsByTemmplet(selectedTemplate)
    if(selectedTranObj)
    {
        selectedTranObj["@page_info"]["selectedPages"] = selectedPagesSeq ;
        selectedTranObj["@page_info"]["importantPages"] = importantPagesSeq ;

        if(!selectedTranObj["action"])
        {
            selectedTranObj["action"] = "U";
        }
    }
    console.log("sandbox updateSelectedTranObjects ..  .",selectedTranObj);
  }

  addSelectedTranObjects(selectedTransaction:any)
  {
    console.log("pushing object in transactions" );
    this.selectedTranObjects.push(selectedTransaction);
  }

  getSelectedTranObjectsByTemmplet(selectedTemplate:any): object
  {
    var selectedTeanObj:any ;
    for(var cn = 0 ; cn<this.selectedTranObjects.length ; cn++ )
    {
        var currTran = this.selectedTranObjects[cn];
        if(currTran["selectedTemplate"] == selectedTemplate)
        {
            selectedTeanObj = currTran;
            break;
        }
    }
    return selectedTeanObj;
  }

  cleareSelectedTranObjects()
  {
    this.selectedTranObjects = [];
    this.pageSelectionDetails = null;
    this.selectedTemplate="";
    console.log("all selected transactions are cleared ")
  }
   // Added by Pravin K on 08-OCT-18 [To get transaction details for new transaction] START
   getTransactionDetails(docId:any, docType:any, ref_ser:any, objName:any, table_name:any, trand_id_col:any, tranId:any, callback:any) {
    this.contentsApiClient.getTransactionDetails(docId, docType, ref_ser, objName, table_name, trand_id_col, tranId).subscribe(
        (result:any) => {
            console.log("getTransactionDetails In Sandbox",result);
            callback(result);
            //this.assocTranscListResp$.next(result);
          }
      );
  }
  // Added by Pravin K on 08-OCT-18 [To get transaction details for new transaction] START

  logDocUsage(docUsageData:any){
      this.contentsApiClient.logDocUsage(docUsageData).subscribe(
              (resp:any) => {
                  console.log("Response on updateDocUsage",resp);
              }
      );
  }

  // Added by Pravin K on 17-APR-19 [to store transaction is session storage] START
  setSessionStorageItem(key:any,data:any){
    sessionStorage.setItem(key,JSON.stringify(data));
  }

  getSessionStorageItem(key:any){
   return sessionStorage.getItem(key);
  }

  removeSessionStorageItem(key:any){
    sessionStorage.removeItem(key);
  }
  // Added by Pravin K on 17-APR-19 [to store transaction is session storage] END

}
