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

import { getHostURL, getAssetImgUrl, getAuthParams } from '../../shared/hostUrl';
//import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
// import { Observable } from 'rxjs/Observable';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, throwError, catchError } from 'rxjs';

import * as moment from 'moment';

@Component({
  selector: 'user-info',
  templateUrl: './user-info.component.html',
  styleUrls: ['./user-info.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class UserInfoComponent {

    @Input('data') dashboardData:any;
    
    userDetails:any = {};
    hostUrl = '';
    ASSET_IMG_URL:any;
    //userImgUrl;
    feedDetails: any = [];
    selReason = 'EXPIRED';
    clientHeight:any;
    imgId:any;
    altImgId:any;
    objName:any;
    actionList:any;
    userRights: any = [];
    
    @Output() onRowSelect: EventEmitter<any> = new EventEmitter();
   
    constructor(private http: HttpClient){}
    
    ngOnInit(){
        console.log('UserInfoComponent Data:',this.dashboardData);
        
        if(this.dashboardData && Array.isArray(this.dashboardData.data) ){
            this.userDetails = this.dashboardData.data[0];
        }else {
            this.userDetails = this.dashboardData.data;
        }
        
        this.hostUrl = getHostURL();
        this.ASSET_IMG_URL = getAssetImgUrl();
        if(!this.hostUrl){
            //this.ASSET_IMG_URL = "/ibase/E12BROWSER/"+this.ASSET_IMG_URL;
        }else {
            this.clientHeight = document.body.clientHeight;
        }
        
        console.log('inside set user rights',this.dashboardData);
        if(this.dashboardData.obj_actions){
            console.log('Inside content view user info ',this.dashboardData.obj_actions);

                if(this.dashboardData.obj_actions)
                {
                    this.dashboardData.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 User Info" ,this.userRights );
            }
        }
        
		console.log("userDetails :" ,this.userDetails );
        if(this.dashboardData && this.dashboardData.feed && this.userDetails ){

            this.dashboardData.feed.forEach(
                (feed:any) => {                        
                        if(feed.type == 'user-image'){
                            this.imgId = this.userDetails[feed.imgId];
                            this.altImgId = this.userDetails[feed.altImgId];
                            this.objName = feed.objName;
                            console.log('this.objName :: ', this.objName);
                        }
                        
                        feed.detail.forEach(
                            (det:any) => {
                                var idList = det["id"].split(',');
                                var displayVal = '';
                                idList.forEach(
                                    (id:any) => {
                                        if(displayVal && this.userDetails[id]){
                                            displayVal = displayVal + (det.seperator || ' ');
                                        }
                                        displayVal = displayVal + (this.userDetails[id] || '');

                                        switch(displayVal){
                                            case "M" :
                                                displayVal = 'Male';
                                                break;
                                            case "F" :
                                                displayVal = "Female";
                                                break;
                                            default :
                                                displayVal = displayVal;
                                                break;
                                        }
                                    }
                                );
                                det["displayVal"] = displayVal;
                            }
                        );

                         this.feedDetails.push(feed);
                    }
            );
        }

        //this.userImgUrl = this.hostUrl + "/ibase/CustomMenuImageServlet?fldValue="+this.imgId+"&ALT_FLD_VALUE="+this.altImgId;
        
        if(this.dashboardData.filterInfo && this.dashboardData.filterInfo.rowData)
        {
            this.onRowSelect.emit(this.dashboardData.filterInfo.rowData);            
        }
        console.log('feedDetails ::',this.feedDetails);
    }
    
    deactivate() {
        var confirmDeactivate = confirm("Confirm Deactivate ?");
        if (confirmDeactivate == true) {
            this.deactivatePatient().subscribe(
                    (resp:any) => {
                        console.log('Resp On Deactivate',resp);
                    }
            );
        }
    }
    
    deactivatePatient(): Observable<any> {
        console.log('this.hostUrl',this.hostUrl);
        
        let url = this.hostUrl + "/ibase/DeactivePatientServlet";
        url = url + "?patient_id="+this.userDetails["CODE"]+"&remarks="+this.selReason;
        
        console.log('deactivate url:: ',url,this.selReason);
        var httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
        var options = { headers: httpHeaders};
        return this.http.get<any>( url, options )
                  /* .map(this.extractData)
                   .catch(this.handleError);*/
                   .pipe(map(this.extractData))
                   .pipe(catchError(this.handleError));
    }
    
    private extractData(res: Response) 
    {
        var body = res.json();
        console.log('extractData[' + JSON.stringify(body) + ']');
        return body || { };
    }
    
    private extractDashboardData(res: Response, metadataName:any) {
        var body = res.json();
        console.log('extractData[' + JSON.stringify(body) + ']');
        localStorage.setItem(metadataName, JSON.stringify(body));
        return body || { };
    }

    private handleError (error: Response | any) {
        var errMsg: string|any;
        if (error instanceof Response)
        {
            //changed by sainath T. to handle error response in ang9
            //const body = error.json() || '';
            error.json().then(body => {
                if (!body) {
                    body = "";
                }
            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);
    }

    getUserImage() {
        //return this.hostUrl + "/ibase/CustomMenuImageServlet?fldValue="+this.imgId+"&ALT_FLD_VALUE="+this.altImgId + '&' + getAuthParams();
        return this.hostUrl + "/ibase/CustomMenuImageServlet?fldValue="+this.imgId+"&ALT_FLD_VALUE="+this.altImgId + '&object='+ this.objName + '&objName='+ this.objName + '&' + getAuthParams();
    }
    
    brokenImage(event:any) {
        event.target.src = this.ASSET_IMG_URL + '/errUser-128.png';
    }
}
