import {Component, Inject} from 'ng-metadata/core';
const templateUrl = require('./kube-deploy-modal.component.html');
const styleUrl = require('./kube-deploy-modal.css');

@Component({
    selector: 'kube-deploy-modal',
    templateUrl,
    styleUrls: [ styleUrl ],
})
export class KubeDeployModalComponent {
    private state
        : 'loadingDeployments'
        | 'readyToDeploy'
        | 'deployingConfiguration'
        | 'cyclingDeployments'
        | 'deployed'
        | 'error';

    private errorMessage: string;

    private deploymentsStatus: { name: string, numPods: number }[] = [];

    constructor(@Inject('ApiService') private ApiService) {
        this.state = 'loadingDeployments';

        ApiService.scGetNumDeployments().then(resp => {
            this.deploymentsStatus = resp.items.map(dep => ({ name: dep.metadata.name, numPods: dep.status.replicas }));
            this.state = 'readyToDeploy';
        }).catch(err => {
            this.state = 'error';
            this.errorMessage = `There are no Quay deployments active in this namespace. \
                                Please check that you are running this \
                                tool in the same namespace as the Quay Enterprise application\
                                Associated error message: ${err.toString()}`;
        })
    }

    deployConfiguration(): void {
        this.ApiService.scDeployConfiguration().then(() => {
            const deploymentNames: string[]= this.deploymentsStatus.map(dep => dep.name);

            this.ApiService.scCycleQEDeployments({ deploymentNames }).then(() => {
                this.state = 'deployed'
            }).catch(err => {
                this.state = 'error';
                this.errorMessage = `Could cycle the deployments with the new configuration. Error: ${err.toString()}`;
            })
        }).catch(err => {
            console.log(err)
            this.state = 'error';
            this.errorMessage = `Could not deploy the configuration. Error: ${err.toString()}`;
        })
    }
}