import { Component, OnInit } from '@angular/core';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { AgreementService } from './service/agreement.service';
import { CheckUserAgreementResponse } from './service/models/check-user-agreement.response';
import { GetUserAgreementResponse } from './service/models/get-user-agreement.response';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';

@Component({
    selector: 'app-agreement',
    templateUrl: './agreement.component.html',
    styleUrls: ['./agreement.component.scss']
})
export class AgreementComponent implements OnInit {

    public agreementContent: string;
    constructor(
        public ts: TranslatorService,
        public cs: CommonService,
        public agreementService: AgreementService,
        public auth: AuthenticationService

    ) { }

    ngOnInit() {
        this.checkUserAgreement();
    }

    checkUserAgreement() {
        this.agreementService.checkUserAgreement(
            () => {
                this.checkUserAgreement();
            }, this.ts.trPK('general', 'retry')).subscribe((result: CheckUserAgreementResponse) => {
                if (this.cs.validResponse(result)) {
                    if (result.IsPatientAlreadyAgreed) {
                       // this.auth.setUserAgreed(true);
                        this.cs.openHome();
                    } else {
                        this.getUserAgreement();
                    }
                }
            });
    }

    private getUserAgreement() {
        this.agreementService.getAgreement(
            () => {
                this.getUserAgreement();
            }, this.ts.trPK('general', 'retry')).subscribe((result: GetUserAgreementResponse) => {
                if (this.cs.validResponse(result)) {
                    this.agreementContent = result.UserAgreementContent;
                }
            });
    }

    public onAcceptClicked() {
        this.agreementService.addUserAgreement(
            () => {
                this.onAcceptClicked();
            }, this.ts.trPK('general', 'retry')).subscribe((result: GetUserAgreementResponse) => {
                if (this.cs.validResponse(result)) {
                    //this.auth.setUserAgreed(true);
                    this.cs.openHome();
                }
            });
    }

    public onRejectClicked() {
        this.auth.clearUser().subscribe(success => {
            this.cs.openHome();
        });
    }



}
