import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { ToastService } from '../services/toast.service';

@Component({
    selector: 'app-profile',
    templateUrl: './profile.page.html',
    styleUrls: ['./profile.page.scss'],
})
export class ProfilePage implements OnInit {
    selected_tab: string = 'MY ORDERS';
    userInfo: any;
    showEdit: boolean = false;

    constructor(
        private location: Location,
        private router: Router,
        private authService: AuthService,
        private toastService: ToastService
    ) { }

    ngOnInit() {        
    }
    
    updateUserInfo() {        
        let tempUserInfo = {
            user_id: this.userInfo.id,
            username: this.userInfo.username,
            user_mobile: this.userInfo.mobile,
            email: this.userInfo.email,
        }
        
        this.authService.updateUser(tempUserInfo).then(() => {
            this.toastService.presentToast("Updated!", "success");
        }, () => {
            this.toastService.presentToast("Failed to update", "danger");
        });
    }

	ionViewDidEnter() {
        this.userInfo = JSON.parse(localStorage.userInfo)['User Info'];
        
        this.authService.getUserDetails(this.userInfo.id).then((data: any) => {
            this.userInfo.mobile = data.mobile;
            this.userInfo.email = data.email;

            let info = JSON.parse(localStorage.userInfo);
            info['User Info'] = this.userInfo;
            localStorage.userInfo = JSON.stringify(info);
        }, () => {
            this.toastService.presentToast("Failed to get user data");
        });

        
		this.selected_tab = '';
		setTimeout(() => {
			this.selected_tab = 'MY ORDERS';
		}, 100);
	}

    back() {
        this.location.back();
    }

	logout() {
		localStorage.clear();
		this.router.navigate(['login']);
	}

}
