package com.qmth.qrzk.web.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qmth.qrzk.dao.repositories.UserMarkRepo;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.model.UserMark;
import com.qmth.qrzk.repository.user.service.SessionUser;

@RestController
@RequestMapping("/usermark")
public class UserMarkController {

	@Autowired private UserMarkRepo userMarkRepo;
	@Autowired private SessionUser sessionUser;
	
	@RequestMapping(method=RequestMethod.GET)
	public List<UserMark> query(){
		User current = sessionUser.getSessionUser();
		return userMarkRepo.findByUserId(current.getId(),new Sort(Direction.DESC,"createdTime"));
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public AjaxResponse create(@RequestBody UserMark userMark){
		AjaxResponse result = null;
		User current = sessionUser.getSessionUser();
		List<UserMark> list = userMarkRepo.findByUserIdAndUrl(current.getId(), userMark.getUrl());
		if(list.size() > 0){
			result = new AjaxResponse(false,"已经收藏了本页");
		}
		else{
			userMark.setUserId(current.getId());
			userMark.setCreatedTime(new Date());
			userMarkRepo.save(userMark);
			result = new AjaxResponse(true);
		}
		return result;
	}
	
	@RequestMapping(value="{id}",method=RequestMethod.DELETE)
	public AjaxResponse remove(@PathVariable Long id){
		userMarkRepo.delete(id);
		return new AjaxResponse(true);
	}
}
