package com.zhiwei.manage.dao;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.mongodb.WriteResult;
import com.zhiwei.manage.bean.Person;

@Component
public class PersonDaoImpl implements PersonDao {

	@Resource(name="mongoTemplate")
	private MongoTemplate mongo;

	@Override
	public void insert(Person person) {
		person.setCreateDate(new Date());
		mongo.insert(person);
	}

	@Override
	public boolean update(Person person) {
		System.out.println(person);
		Query query = Query.query(Criteria.where("_id").is(person.getPersonId()));
		Update update = new Update();
		update.set("username", person.getUsername());
		update.set("password", person.getPassword());
		update.set("lv", person.getLv());
		WriteResult wr = mongo.updateFirst(query, update, Person.class);
		int result = wr.getN();
		return result == 1 ? true : false;
	}

	@Override
	public List<Person> findAll(int pageNo,int pageSize) {
		return mongo.find(Query.query(Criteria.where("_id").exists(true)).skip((pageNo-1)*pageSize).limit(pageSize), Person.class);
	}

	@Override
	public Person findById(String personId) {	
		return mongo.findById(personId, Person.class);
	}

	@Override
	public boolean delete(List<String> personId) {
		WriteResult wr=mongo.remove(Query.query(Criteria.where("_id").in(personId)),Person.class);
		int result=wr.getN();
		return result == 1 ? true : false;
	}

	@Override
	public Person findByUsername(String username) {
		return mongo.findOne(Query.query(Criteria.where("username").is(username)), Person.class);
	}

	@Override
	public List<Person> findAllByUsername(String username, int pageNo, int pageSize) {
		return mongo.find(Query.query(Criteria.where("username").is(username)).skip((pageNo-1)*pageSize).limit(pageNo), Person.class);
	}

	@Override
	public int findAllCount() {
		return (int) mongo.count(Query.query(Criteria.where("username").exists(true)), Person.class);
	}

	@Override
	public int findUserCount(String username) {
		return (int) mongo.count(Query.query(Criteria.where("username").exists(true)), Person.class);
	}

}
