import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BaseComponent } from '../base/base.component';
import { HomeService } from '../_services/index';
import { StatsService } from '../_services/index';
import { UserService, AlertService } from '../_services';
import { AuthenticationService } from '../_services/authentication.service';
import { User } from '../_models';
import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
    moduleId: module.id.toString(),
    templateUrl: 'home.component.html',
    styleUrls: ['home.component.scss']
})

export class HomeComponent extends BaseComponent implements OnInit, OnDestroy {
    // Public
    public loading = false;
    public users: any;
    public _user: User = null;

    /* pagination */
    public itemsPerPage = 5;
    public offset = 0;
    public paginator = false;
    public total = 0;
    public currentPage = 1;

    // Private
    private sub: any;
    private timeout: any;

    constructor(
        private homeService: HomeService,
        private statsService: StatsService,
        private auth: AuthenticationService,
        private router: Router,
        private userService: UserService,
        private alertService: AlertService
    ) {
        super();
        this.itemsPerPage = this.CONSTANTS.users.perPage;
    }

    ngOnInit() { }

    ngOnDestroy() { }

    setTemp(user: User){
        this._user = user;
    }

    removeTemp(){
        this._user = null;
    }

    deleteUser(id: number) {
        this.userService.delete(id).subscribe((response: any) => {
            this.alertService.success("Usuario eliminado correctamente.", false);
            this.loadLazy({first: "0"});
        });
    }


    loadLazy(e: any) {
        console.log(e);

        let current = (e.first / this.CONSTANTS.users.perPage) + 1; 

        const data = {
            perPage: this.CONSTANTS.users.perPage,
            page: current,
        };

        this.loading = true;
        this.userService.getUsers(data).subscribe((users: any) => {
            this.loading = false;
            this.users = users.data;
            this.total = users.total;
            this.currentPage = users.current_page;

            if (this.total > this.itemsPerPage) {
                this.paginator = true;
            }

        }, err => this.handleError(err));
    }


    private handleError(error: any): Promise<any> {
        console.error(this.constructor.name + ': An error occurred', error);
        if (error.error.msg === this.CONSTANTS.servicesMsg.NOT_AUTHORIZED) {
            this.auth.logout();
            this.router.navigate(['/login']);
        }
        return Promise.reject(error.message || error);
    }
}
