import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import * as uuid from 'uuid';
import CartItem from '../models/cart-item';

@Injectable({
	providedIn: 'root'
})
export class OrderService {
	orders: any = [];

	constructor(
		private storage: Storage
	) { }

	async createOrder(cart_items: Array<CartItem>, calculated_total: number, promocode: string) {
		return this.storage.get('orders').then((data: string) => {
			if (data === null) {
				this.orders.push({
					id: uuid(),
					calculated_total: calculated_total,
					promocode: promocode,
					creation_time: new Date(),
					order_items: cart_items
				});
				this.storage.set('orders', JSON.stringify(this.orders)).then((data) => {
					console.log(data);
				});
			} else {
				this.orders = JSON.parse(data);
				this.orders.push({
					id: uuid(),
					calculated_total: calculated_total,
					promocode: promocode,
					creation_time: new Date(),
					order_items: cart_items
				});
				this.storage.set('orders', JSON.stringify(this.orders));
			}
		}, () => {
			console.log("failed");
		});
	}

	async getCreatedOrders() {
		return await this.storage.get('orders').then((data: string) => {
			if (data === null) {
				return [];
			} else {
				return JSON.parse(data);
			}
		});
	}

}
