package com.example.service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.domain.Items;
import com.example.domain.SalesLog;
import com.example.domain.Shoes;
import com.example.repository.SalesLogRepository;

@Service
public class SalesLogService {
	@Autowired
	SalesLogRepository salesLogRepository;
	@Autowired
	ShoesService shoesService;
	
	public List<SalesLog> findAll(){
		return salesLogRepository.findAll();
	}
	
	public SalesLog findOne(Integer id){
		return salesLogRepository.findOne(id);
	}
	
	public SalesLog create(SalesLog salesLog){
		return salesLogRepository.save(salesLog);
	}
	
	public void update(Integer userId, ArrayList <Items> cart){
		java.util.Date d1 = new java.util.Date();
		//d1をSQL.DATE型に変換してtodayに代入
		java.sql.Date today = new java.sql.Date(d1.getTime());
		//カートに入っている靴の種類文処理
		for(int i = 0; i < cart.size(); i++){
			//在庫数を購入数分減らす処理
			Shoes shoes = new Shoes(); 
			shoes = shoesService.findOne((cart.get(i)).getShoesId());
			shoes.setStock(shoes.getStock() - (cart.get(i)).getQuantity());
			shoesService.update(shoes);
			//購入履歴に情報を追加する処理
			SalesLog salesLog = new SalesLog();
			salesLog.setUserId(userId);
			salesLog.setShoesId((cart.get(i)).getShoesId());
			salesLog.setQuantity((cart.get(i)).getQuantity());
			salesLog.setPrice((cart.get(i)).getPrice());
			salesLog.setCreated(today);
			salesLogRepository.save(salesLog);
		}
	}
	
	public List<SalesLog> history(Integer id) {
		return salesLogRepository.history(id);
	}
	
	public List <SalesLog> historyDetails(Date created, Integer id) {
		return salesLogRepository.historyDetails(created, id);
	}
	
	public List<SalesLog> searchPrice(Integer lowPrice, Integer highPrice, Integer id){
		return salesLogRepository.searchPrice(lowPrice, highPrice, id);
	}
}
