package com.pas.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.pas.dao.UserDao;
import com.pas.model.AuthExternal;
import com.pas.model.User;

public class UserDaoImpl implements UserDao {
	@Autowired
	private SessionFactory session;
	
	@Override
	public void add(User user) {
		session.getCurrentSession().save(user);
	}
	
	@Override
	public void edit(User user) {
		session.getCurrentSession().update(user);
	}
	
	@Override
	public void delete(int userId) {
		session.getCurrentSession().delete(userId);
	}
	
	@Override
	public User getUser(int userId) {
		return (User) session.getCurrentSession().get(User.class, userId);
	}
	
	@Override
	public List<User> getAllUser() {
		return (List<User>) session.getCurrentSession().createQuery("from " + User.class.getName()).list();
	}
	
	@Override
	public Integer createExternalConnector(AuthExternal auth) {
		return (Integer) session.getCurrentSession().save(auth);
	}

	@Override
	public User getUserByExternalConnector(String service, String username) {
		List<AuthExternal> authExternals = session.getCurrentSession().createQuery("from " + AuthExternal.class.getName() + " where username= '" + username + "'").list();
		
		User user = new User();
		for (AuthExternal authExternal : authExternals) {
			user = (authExternal.getId().getService().equals(service) ? authExternal.getUser() : null); 
		}
		
		return user;
	}

	@Override
	public User getUserByUserName(String username) {
		List<User> userlst = (List<User>) session.getCurrentSession().createQuery("from " + User.class.getName() + " where username= '" + username + "'").list();
		
		return (!userlst.isEmpty() ? userlst.get(0) : new User());
	}
	
	@Override
	public List<AuthExternal> getExternalConnector(String service, String username) {
		return (List<AuthExternal>) session.getCurrentSession().createQuery("from " + AuthExternal.class.getName() + " where username= '" + username + "'").list();
	}

	@Override
	public List<User> findByAuthorization(String username, String pwd) {
		return (List<User>) session.getCurrentSession().createQuery("from " + User.class.getName() + " where username= '" + username + "' and password= '" + pwd + "'").list();
	}
}