import { Component, OnInit, Input, OnChanges, DoCheck, } from '@angular/core';
import { Breadcrumbs } from '../ecm-breadcrumbs/ecm-breadcrumbs.component';
import { MdSnackBar } from '@angular/material';

import { Store } from '@ngrx/store';
import { AppState } from '../ecm-store/reducers';
import { OrderActions} from '../ecm-store/actions';
import { EcmOrderService } from './ecm-order.service';
import { Observable } from 'rxjs/Observable';
import { Router, ActivatedRoute } from '@angular/router';
import { Order } from '../ecm-model/order-model';


@Component({
  selector: 'app-ecm-order',
  templateUrl: './ecm-order.component.html',
  styleUrls: ['./ecm-order.component.css'],
  providers:[EcmOrderService]
})
export class EcmOrderComponent implements OnInit {

    ordersList : any;
    ordersItems : Observable<Order[]>;
    totalPrice: number = 0;
    orderDate: string;
    
   constructor( private route: ActivatedRoute, public breadcrumbSerivce: Breadcrumbs, public snackBar: MdSnackBar,  private store: Store<AppState>, private router: Router,  private orderActions: OrderActions , public orderService: EcmOrderService) {}
      
  ngOnInit() {
      let breadcrumb = [{label: 'Home', url: '/home'}, {label: 'Orders', url: 'javascript:void(0)'}];
      this.breadcrumbSerivce.breadcrumbs = breadcrumb;
      this.ordersItems = this.store.select( 'orderItems' );
      this.store.dispatch(this.orderActions.loadOrderItems());
      this.loadOrders();
  }
  
  
  dispDateFormat = 'dd MMM yyyy - EEEE';
  toDate( dateStr ) {
     let date: Date = new Date();
      //2017-11-07T00:00:00
      var parts = dateStr.split( "-" );
      date = new Date(parts[2], parts[1] - 1, parts[0]);
      console.log("the date try", date);

      if(date.toString() === 'Invalid Date'){
          date = new Date(dateStr);
          console.log("the date catch", date);
      }
      return date;
  }

  
  loadOrders() {
      this.store.select( 'orderItems' ).subscribe( orderItems => {
          console.log( 'loadUser orderList >> ', orderItems );
          this.ordersList = orderItems;
      });
  }
  
  invoiceDetail(){
      this.openSnackBar( 'The Page is redirected to Invoice' );
  }
  orderDetail(){
      this.router.navigate( ['/orderDetail'] );
  }
  
  openSnackBar( message: string ) {
      this.snackBar.open( message, '', {
          duration: 2000,
      });
  }
  
}
