
import { Component, View, NgFor } from 'angular2/angular2';
import { RouterLink } from 'angular2/router';
import { ObservableWrapper } from 'angular2/src/core/facade/async';
import { DataService } from '../../services/data-service';
import { StorageService } from "../../services/storage-service";
import { ModalService } from "../../services/modal-service";
import { CurrencyPipe } from '../../pipes/currency-pipe';


@Component({
  selector: 'shoppingItems',
  providers: [StorageService, ModalService],
  templateUrl: 'app/components/items/items-component.html',
  directives: [RouterLink, NgFor],
  pipes: [CurrencyPipe]
})
export class ItemsComponent {
  title: string;
  items: any[];
  public cost: number;
  tax: number;

  constructor(private storageService: StorageService, private modalService: ModalService) {
    this.title = "Items";
    this.tax = 0.07;
    
    //force localStorage
    this.storageService.init();

    localforage.getItem("cost", (err, value) => {
      if (err) {
        console.log(err);
      }
      else {
        if (value === null) {
          this.cost = 0;
        }
        else {
          this.cost = value;
        }
      }
    })

    localforage.getItem("items", (err, value) => {
      if (err) {
        console.log(err)
      }
      else {
        
        //there were no items saved
        if (value === null) {
          this.items = [];
        }
        //there were items saved
        else {
          this.items = value;
        }

      }
    })

  }
  
  //open modal to add new item
  addItem() {
    this.modalService.open();
  }
  
  //add item
  add(name: string, price: string) {
    let newItem = new DataService(name, price);
    
    //have to convert this to a number so we can add up the total cost
    let realPrice: number = parseInt(newItem.price);
    
    //set the cost of the item
    this.cost = this.cost + realPrice + this.tax;

    this.items.push(newItem);

    this.storageService.save("items", this.items);
    this.storageService.save("cost", this.cost);

    this.modalService.close();
  }
  
  //user decides to not add item
  close() {
    this.modalService.close();
  }
  
  //user removes item
  removeItem(item: any) {
    this.items.splice(this.items.indexOf(item), 1);

    this.cost = this.cost - item.price-this.tax;
    
    this.storageService.save("cost", this.cost); 
    this.storageService.save("items", this.items);
    
    navigator.vibrate(500);
  }

}




