package com.braintree.service.impl;

import com.braintree.daos.BrainTreeAccessTokenDao;
import com.braintree.model.PaypalAccessTokenModel;
import com.braintree.service.BrainTreeAccessTokenService;
import com.braintree.util.GenericBuilder;
import de.hybris.platform.commerceservices.util.GuidKeyGenerator;
import de.hybris.platform.servicelayer.model.ModelService;

import java.util.Optional;

public class DefaultBraintreeAccessTokenService implements BrainTreeAccessTokenService {

    private BrainTreeAccessTokenDao braintreeAccessTokenDao;

    private GuidKeyGenerator guidKeyGenerator;

    private ModelService modelService;

    public Optional<PaypalAccessTokenModel> getPaypalAccessToken(String guid) {
        return braintreeAccessTokenDao.findAccessTokenByGuid(guid);
    }

    public String savePaypalAccessToken(String accessToken) {
        String guid = guidKeyGenerator.generate().toString();

        PaypalAccessTokenModel paypalAccessToken = GenericBuilder.of(PaypalAccessTokenModel::new)
                .with(PaypalAccessTokenModel::setAccessToken, accessToken)
                .with(PaypalAccessTokenModel::setGuid, guid)
                .build();
        modelService.save(paypalAccessToken);

        return guid;
    }

    public void removePaypalAccessToken(String accessTokenGuid) {
        getPaypalAccessToken(accessTokenGuid).ifPresent(accessToken -> modelService.remove(accessToken));
    }

    public void setBraintreeAccessTokenDao(BrainTreeAccessTokenDao braintreeAccessTokenDao) {
        this.braintreeAccessTokenDao = braintreeAccessTokenDao;
    }

    public void setGuidKeyGenerator(GuidKeyGenerator guidKeyGenerator) {
        this.guidKeyGenerator = guidKeyGenerator;
    }

    public void setModelService(ModelService modelService) {
        this.modelService = modelService;
    }

}
