/*******************************************************************************
 * Copyright 2018 The MIT Internet Trust Consortium
 *
 * Portions copyright 2011-2013 The MITRE Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package cz.muni.ics.oauth2.repository.impl;

import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.repository.OAuth2ClientRepository;
import cz.muni.ics.util.jpa.JpaUtil;
import org.eclipse.persistence.exceptions.DatabaseException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.Collection;

/**
 * @author jricher
 *
 */
@Repository
@Transactional(value="defaultTransactionManager")
public class JpaOAuth2ClientRepository implements OAuth2ClientRepository {

	@PersistenceContext(unitName="defaultPersistenceUnit")
	private EntityManager manager;

	public JpaOAuth2ClientRepository() {

	}

	public JpaOAuth2ClientRepository(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public ClientDetailsEntity getById(Long id) {
		return manager.find(ClientDetailsEntity.class, id);
	}

	@Override
	public ClientDetailsEntity getClientByClientId(String clientId) {
		TypedQuery<ClientDetailsEntity> query = manager.createNamedQuery(
				ClientDetailsEntity.QUERY_BY_CLIENT_ID, ClientDetailsEntity.class
		);
		query.setParameter(ClientDetailsEntity.PARAM_CLIENT_ID, clientId);
		return JpaUtil.getSingleResult(query.getResultList());
	}

	@Override
	public ClientDetailsEntity saveClient(ClientDetailsEntity client) {
		return JpaUtil.saveOrUpdate(manager, client);
	}

	@Override
	public void deleteClient(ClientDetailsEntity client) {
		ClientDetailsEntity found = getById(client.getId());
		if (found != null) {
			Collection<ClientDetailsEntity> childClients = getClientsByParentClientId(client.getId());
			for (ClientDetailsEntity child: childClients) {
				manager.remove(child);
			}
			manager.remove(found);
		} else {
			throw new IllegalArgumentException("Client not found: " + client);
		}
	}

	@Override
	public ClientDetailsEntity updateClient(Long id, ClientDetailsEntity client) {
		// sanity check
		client.setId(id);

		return JpaUtil.saveOrUpdate(manager, client);
	}

	@Override
	public Collection<ClientDetailsEntity> getAllClients() {
		TypedQuery<ClientDetailsEntity> query = manager.createNamedQuery(
				ClientDetailsEntity.QUERY_ALL, ClientDetailsEntity.class
		);
		return query.getResultList();
	}

	@Override
	public Collection<String> getResourceIdsForClientID(String clientId) {
		TypedQuery<String> query = manager.createNamedQuery(
				ClientDetailsEntity.QUERY_RESOURCE_IDS_BY_CLIENT_ID, String.class
		);
		query.setParameter(ClientDetailsEntity.PARAM_CLIENT_ID, clientId);
		return query.getResultList();
	}

	@Override
	public void deleteClientByClientId(String clientId) {
		Query query = manager.createNamedQuery(ClientDetailsEntity.DELETE_BY_CLIENT_ID);
		query.setParameter(ClientDetailsEntity.PARAM_CLIENT_ID, clientId);
		query.executeUpdate();
	}

	private Collection<ClientDetailsEntity> getClientsByParentClientId(Long parentId) {
		TypedQuery<ClientDetailsEntity> query = manager.createNamedQuery(
				ClientDetailsEntity.QUERY_ALL_BY_PARENT_CLIENT_ID, ClientDetailsEntity.class
		);
		query.setParameter(ClientDetailsEntity.PARAM_PARENT_CLIENT_ID, parentId);
		return query.getResultList();
	}

}
