import { Component, OnInit } from '@angular/core';
import { first } from 'rxjs/operators';
import { AlertService, UserService, AuthenticationService } from '@/_services';
import {User} from "@/_models";
import {CompanyService} from "@/_services/company.service";
import {Company} from "@/_models/company";
import {Router} from "@angular/router";

@Component({ templateUrl: 'users.component.html' })
export class UsersComponent implements OnInit {
    currentUser: User;
    users = [];
    companies = [];

    constructor(
        private authenticationService: AuthenticationService,
        private userService: UserService,
        private router: Router,
        private companiesService: CompanyService,
    ) {
        this.currentUser = this.authenticationService.currentUserValue;
    }

    ngOnInit() {
        this.loadAllUsers();
        this.loadAllcompanies();
    }
    private loadAllUsers() {
        this.userService.getAll()
            .pipe(first())
            .subscribe(users => this.users = users);
    }

    deleteUser(id: number) {
        this.userService.delete(id)
            .pipe(first())
            .subscribe(() => this.loadAllUsers());
    }

    changeAdminForUser(user: User) {
        if (!user.approved) {
            alert("User must approved before set as Admin");
            return;
        }
        user.is_admin = !user.is_admin;
        this.userService.register(user)
            .pipe(first())
            .subscribe(() => this.loadAllUsers());
    }

    approveUser(user: User) {
        user.approved = true;
        this.userService.register(user)
            .pipe(first())
            .subscribe(() => this.loadAllUsers());
    }

    private loadAllcompanies() {
        this.companiesService.getAll()
            .pipe(first())
            .subscribe(companies => this.companies = companies);
    }

    deleteCompany(id: number) {
        this.companiesService.delete(id)
            .pipe(first())
            .subscribe(() => this.loadAllcompanies());
    }

    loadCompany(company: Company) {

        this.router.navigate(['/companies'], { queryParams: company });
    }

}
