import { Component } from '@angular/core';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';

import {AppState} from './ecm-store/reducers';
import {CartActions, CategoryActions, MenuActions, WishListActions} from './ecm-store/actions';

import { HostUrlService } from './host-url.service';
import { Store } from '@ngrx/store';

import { ECMSigninService } from './ecm-signin/ecm-signin.service';

import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Rx";
@Component({
  selector: 'ecm-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]
})
export class AppComponent {
  title = 'Proteus ECM';
  location: Location;
  locationPath: string = "";
  
  constructor(location: Location, private store: Store<AppState>, public signinService: ECMSigninService, private http:Http, private cartAction: CartActions, private categoryAction: CategoryActions, private menuAction:MenuActions, private wishListAction: WishListActions, public hostUrlService : HostUrlService) { 
    this.location = location; 
    this.locationPath = this.location.path(true);
    console.log( ' this.locationPath[' + this.locationPath + ']');
    var url = '';
    if( document.getElementById("hostUrl") ){
	    url= (<HTMLInputElement>document.getElementById("hostUrl")).value;  
    }
    this.hostUrlService.hostUrl = url;
    setTimeout(() => {
        this.checkAppState();
    }, 1000);
  }
  checkAppState(){
   this.setItem('jwtToken', this.get('jwtToken'), false );
   this.setItem('appstate', this.get('app_stat'), true );
   this.setItem('TOKEN_ID', this.get('TOKEN_ID'), true ); 
   this.setItem('ECM_TYPE', this.get('ECM_TYPE'), true );
   this.setItem('SITE_CODE', this.get('SITE_CODE'), true );
   
     this.signinService.fetchUserData().subscribe(
     response => {
         if(response){
             this.store.dispatch(this.cartAction.loadCartItems());
             this.store.dispatch(this.wishListAction.loadWishlistItems());                   
         }
     }
    )
   this.store.dispatch(this.categoryAction.loadCategories());
   this.store.dispatch(this.menuAction.loadMenu());
   
  }
  get(name){
   var retVal = 'undefined';
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(this.locationPath))
   {
     console.log( 'name[' + name + '] decodeURIComponent(name[1]) [' + decodeURIComponent(name[1]) + ']');
     retVal = decodeURIComponent(name[1]);
   }
   console.log( 'retVal[' + retVal + ']');
   return retVal;
  }
  setItem(key, data, isUndefined){
   if (typeof(Storage) != 'undefined' && ( data !== 'undefined' || isUndefined ) ) 
   {
      localStorage.setItem(key, data);
   }
   else
   {
      console.log('Sorry, your browser does not support Web Storage...');
   }
  }
}
