import { Component, OnInit } from '@angular/core';
import { OrderService } from '../services/order.service';
import * as moment from 'moment';
import { ICart } from '../cart/cart.page';
import { Router } from '@angular/router';
import { ToastService } from '../services/toast.service';
import { LoadingController } from '@ionic/angular';

@Component({
    selector: 'app-orders',
    templateUrl: './orders.component.html',
    styleUrls: ['./orders.component.scss'],
})
export class OrdersComponent implements OnInit {
    userOrders: any = [];
    userInfo: any;
    userCart: ICart = {
        orderedlist: []
    };
    allOrderStatus: any = [];

    selectedOrder: any;

    showAddReview: boolean = false;

    tempReview = {
        app_user: {
            user_id: null
        },
        comment: '',
        rating: null,
    };

    loader: any;

    constructor(
        private orderService: OrderService,
        private router: Router,
        private toastService: ToastService,
        public loadingController: LoadingController
    ) { }

    async presentLoading() {
        this.loader = await this.loadingController.create({
            message: 'Please wait...',
            spinner: 'dots',
            mode: 'ios'
        });
        await this.loader.present();
    }


    submitFeedbackForOrder() {
        this.tempReview.app_user.user_id = this.userInfo.id;
        

        let orderToReview: any = JSON.parse(JSON.stringify(this.selectedOrder));

        orderToReview.orderedlist = this.getOrderInUsercardFormat(this.selectedOrder.orderedlist);

        orderToReview.rating = this.tempReview;

        console.log(orderToReview);

        this.orderService.updateOrder(orderToReview).then(() => {
            this.toastService.presentToast("Review sent", "success");

            this.selectedOrder.rating = orderToReview.rating;

            this.tempReview = {
                app_user: {
                    user_id: ''
                },
                comment: '',
                rating: '',
            };

            this.showAddReview = false;

        }, () => {
            this.toastService.presentToast("Failed to send review", "danger");
        });
    }

    getOrderInUsercardFormat(orderedlist: any) {
        let compiledOrderedList: any = [];

        for (let i = 0; i < orderedlist.length; i += 1) {
            compiledOrderedList.push({
                mall_id: orderedlist[i].mall_id,
                outlet_id: orderedlist[i].outlet_id,
                menuitem_id: orderedlist[i].menuitems.menuitem_id,
                quantity: orderedlist[i].quantity,
                pickup_time: moment().add(moment.duration(orderedlist[i].menuitems.wait_duration).asMinutes(), 'minutes').format(),
                take_away: true,
                order_status: null,
                total_price: orderedlist[i].total_price,
                soft_delete: false,
            });
        }

        return compiledOrderedList;
    }

    ngOnInit() {
        this.userInfo = JSON.parse(localStorage.userInfo)['User Info'];

        this.presentLoading();

        this.orderService.getOrders(this.userInfo.id).then((resp: any) => {
            this.userOrders = resp.reverse();

            this.loader ? this.loader.dismiss() : null;
        }, (err) => {
            console.log(err);
            this.toastService.presentToast("Failed to get orders");

            this.loader ? this.loader.dismiss() : null;
        });

        this.orderService.getAllOrderStatus().then((data) => {
            this.allOrderStatus = data;
        }, (err) => {
            console.log(err);
        })
    }

    getOrderStatusName(id: number) {
        try {
            if (id) {
                return this.allOrderStatus.find(status => status.orderstatus_id === id).orderStatus;
            } else {
                return '-';
            }
        } catch {
            return '-';
        }
    }

    getFormattedDate(date, format) {
        return moment(date).format(format);
    }

    reOrder(orderedlist: any) {
        for (let i = 0; i < orderedlist.length; i += 1) {
            this.userCart.orderedlist.push({
                mall_id: orderedlist[i].mall_id,
                outlet_id: orderedlist[i].outlet_id,
                menuitem_id: orderedlist[i].menuitems.menuitem_id,
                quantity: orderedlist[i].quantity,
                pickup_time: moment().add(moment.duration(orderedlist[i].menuitems.wait_duration).asMinutes(), 'minutes').format(),
                take_away: true,
                order_status: null,
                total_price: orderedlist[i].total_price,
                soft_delete: false,
            });
        }
        localStorage.userCart = JSON.stringify(this.userCart);
        this.router.navigate(['/cart']);
        console.log(this.userCart);
    }

}
