import { Injectable }       from '@angular/core';
// import { Observable }       from 'rxjs/Observable';
import { Observable }       from 'rxjs';
import { HttpClient, HttpResponse, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { getHostURL } from '../../content-library.component';
import { Content } from '../models';
// import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
// import 'rxjs/Rxjs';
import { throwError, catchError } from 'rxjs';

@Injectable()
export class ContentsApiClient {

  //private SERVICE_URL = '/contentLibrary/service/';  // URL to web service
  API_URL = '/ibase/rest/'; // URL to web service
  SERVICE_URL = '';
  constructor(private http: HttpClient) {
      this.SERVICE_URL = getHostURL() + this.API_URL;
      console.log('getHostURL in constructor of contentsApiClient.service',this.SERVICE_URL);
  }
  /**
   * Retrieves all contents for given userid
   */
  getContentList(fileData: string): Observable<any> {
      
    console.log('--Inside getContentList service--fileData:['+fileData+']');
    if( fileData && fileData !== 'DUMMY' )
    {
      //console.log('Subject Initiated ...');
      var fileDataSubject = new BehaviorSubject<any>({});
      
      //console.log('Observable Initiated ...');
      var currentData = fileDataSubject.asObservable();
      
      var fileJSONData = JSON.parse(fileData);
      //console.log('Subject Next Called ...');
      fileDataSubject.next(fileJSONData);
      
      //console.log('Observable returned ...');
      return currentData;
    }
    else
    {
      let url = this.SERVICE_URL + 'UserDocContents';
      let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
      let options = {headers: headers};
      return this.http.get( url, options )
                //  .map(this.extractData)
                //  .catch(this.handleError);
                 .pipe(map(this.extractData as any))
                 .pipe(catchError(this.handleError));
    }
  }
  
  
  /**
   * Updates content for the given docId
   */
  
  updateContent( content: Content ) {
      //console.log( "updateContent method Called" );
      let url = this.SERVICE_URL + 'UserDocContents/' +content.docId;
      let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
      let options = {headers: headers};
      
     return this.http.post<any>(url, JSON.stringify(content) , options)
          .pipe( map( (res) => this.extractData(res) ) );
     
  }
  
  /**
   * Deletes content of the given docId
   */
  
  deleteContent( docId:any ) {
      //console.log( "deleteContent Called" );

      let url = this.SERVICE_URL + 'UserDocContents/' +docId;
      return this.http.delete<any>( url, {})
                      .pipe( map(res => res.json()) );
  }

   /**
   * Update pin status of the given docId
   */
  
  updatePinned(doc_id :any, status:any)
  {
      //console.log("updatePinStatus method Called ::", doc_id , status);
      let url = this.SERVICE_URL + 'UserDocContents/updateStatus/' + doc_id;
      let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
      let options = {headers: headers};

      this.http.post( url , JSON.stringify(status), options)
      .subscribe(data => {
         console.log("Updated pin");
      }, error => {
          console.log(error.json());
      });
  }

  updateDates(doc_id:any)
  {
      //console.log("updating dates ::",doc_id);
      let url = this.SERVICE_URL + 'UserDocContents/updateDates/' + doc_id;
      let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
      let options = {headers: headers};
      
      this.http.post( url ,  options)
      .subscribe(data => {
         //console.log("Updated date", );
      }, error => {
          console.log(error.json());
      });

  }
  
  getDocContent(docId:any){
      let url = this.SERVICE_URL + 'DocContent/'+docId;
      
      let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
      let options = {headers: headers};
      return this.http.get<any>( url, options )
                 .pipe(map( (res:any) => this.extractData(res) ));
    }

  
  getUserRights()
  {
      let OBJ_NAME = 'content_library';
      let userRightsURL = getHostURL() + '/ibase/WEBITMRIARequestHandlerServlet';
      let Url = userRightsURL + "?ACTION=OBJ_ACTIONS&OBJ_NAME=content_library&FORMAT=JSON";  
      //let headers = new HttpHeaders({ 'Content-Type': 'application/json' });
      let headers = new HttpHeaders({ 'Content-Type': 'text/html' });
      let options = {headers: headers};
      console.log( "URL for getUserRights method >>>>>" , Url ); 
      return this.http.get<any>( Url , options) 
      .pipe(map( (res:any) => this.extractData(res) ));
         
  }
  
  private extractData(res: HttpResponse<any>) {
         // let body = res.json();
          console.log('extractData[' + JSON.stringify(res) + ']');
          return res || { };
      }
      
   private handleError (error: HttpErrorResponse | any) {
      // In a real world app, we might use a remote logging infrastructure
      let errMsg: string;
      if (error instanceof HttpErrorResponse) {
        //const body = error.json() || '';
        //const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''}`;// ${err}`;
      } else {
        errMsg = error.message ? error.message : error.toString();
      }
      console.error('Service handleError:' + errMsg);
      // return Observable.throw(errMsg);
      return throwError(errMsg);
    }
   
   deactivateDocContent(docId:any)
   {
       let url = this.SERVICE_URL + 'UserDocContents/' + docId;
       let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
       let options = {headers: headers};
       return this.http.delete<any>( url , options) 
       .pipe(map( (res:any) => this.extractData(res) ));

   }
   
  getAssociateObjList(docType:any, docId:any)
  {
      let URL = getHostURL() + '/ibase/rest/AssocObjDetails/'+docType+'/'+docId;
      let headers = new HttpHeaders({ 'Content-Type': 'text/html' });
      let options = {headers: headers};
      console.log( "URL for getAssociateObjList method >>>>>" , URL ); 
      return this.http.get<any>( URL , options) 
      .pipe(map( (res:any) => this.extractData(res) ));
  }
  
  getAssocTransList(docType:any, docId:any, refSer:any,obj_name:any, table_name:any , trand_id_col:any)
  {
      let URL = getHostURL() + '/ibase/rest/AssocTransList/'+docType+'/'+docId+'/'+refSer+'/'+obj_name+'/'+table_name+'/'+trand_id_col;
      let headers = new HttpHeaders({ 'Content-Type': 'text/html' });
      let options = {headers: headers};
      console.log( "URL for getAssocTransList method >>>>>  . " , URL ); 
      return this.http.get<any>( URL , options) 
      .pipe(map( (res:any) => this.extractData(res) ));
  }
  /* Added by Pravin K on 25-SEP-18 [to get getObjLinksDetails ] START */
  getObjLinksDetails(objName:any,targetObjName:any)
  {
      let URL = getHostURL() + '/ibase/rest/objLinksDetails/'+objName+'/'+targetObjName;
      let headers = new HttpHeaders({ 'Content-Type': 'text/html' });
      let options = {headers: headers};
      console.log( "URL for getObjLinksDetails method >>>>>  . " , URL ); 
      return this.http.get<any>( URL , options) 
      .pipe(map( (res:any) => this.extractData(res) ));
  }
  /* Added by Pravin K on 25-SEP-18 [to get getObjLinksDetails ] END */
  
  updateDocTransPageInfo(transObject : object)
  {
      console.log('updateDocTransPageInfotransList [',transObject);
      var transListStr = JSON.stringify( transObject);
      console.log('updateDocTransPageInfo transListStr [',transListStr);

      let URL = getHostURL() + '/ibase/rest/UpdateDocTransPageInfo/';
      let headers = new HttpHeaders({ 'Content-Type': 'text/html' });
      let options = {headers: headers};
      console.log( "URL for UpdateDocTransPageInfo method >>>>>" , URL ); 
      return this.http.post<any>( URL ,transListStr, options) 
      .pipe(map( (res:any) => this.extractData(res) ));
  }

   // 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)
  {
      let URL = getHostURL() + '/ibase/rest/getTransctionDetails/'+docId+'/'+docType+'/'+ref_ser+'/'+objName+'/'+table_name+'/'+trand_id_col+'/'+tranId;
      let headers = new HttpHeaders({ 'Content-Type': 'text/html' });
      let options = {headers: headers};
      console.log( "URL for getTransactionDetails method >>>>>  . " , URL ); 
      return this.http.get<any>( URL , options) 
      .pipe(map( (res:any) => this.extractData(res) ));
  }
    // Added by Pravin K on 08-OCT-18 [To get transaction details for new transaction] END 
    
  logDocUsage( docUsageData:any ) {
      let url = this.SERVICE_URL + 'api/LogDocUsage';
      let headers = new HttpHeaders( { 'Content-Type': 'application/json' });
      let options = {headers: headers};
      console.log('Doc Usage Data in content service',url,docUsageData);
      
      return this.http.post<any>(url, JSON.stringify(docUsageData) , options)
          .pipe(map( (res:any) => this.extractData(res) ));
  }
} 
