package com.style24.batch.biz.job.goods;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbGoodsEpService;
import com.style24.persistence.domain.GoodsEp;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.util.GagaFileUtil;

/**
 * 네이버 판매지수EP 생성
 *
 * @author gagamel
 * @since 2021. 6. 15
 */
@Component
@Slf4j
public class TsbNaverSellEp extends TsbAbstractJob<Collection<GoodsEp>, Collection<GoodsEp>, String> {

	@Autowired
	private TsbGoodsEpService naverEpService;

	@Autowired
	private Environment env;

	@Override
	public Collection<GoodsEp> read() throws Exception {
		// 네이버 판매지수EP 목록
		return naverEpService.getNaverSellEpList();
	}

	@Override
	public Collection<GoodsEp> process(Collection<GoodsEp> goodsEpList) throws Exception {
		return goodsEpList;
	}

	@Override
	public String write(Collection<GoodsEp> goodsEpList) throws Exception {
		if (goodsEpList != null && !goodsEpList.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			this.setEpTitle(sb);

			for (GoodsEp goodsEp : goodsEpList) {
				this.setEpInfo(sb, goodsEp);
			}

			String uploadPath = GagaFileUtil.getConcatenationPath(env.getProperty("ep.file.path"), "iStyle24ProductFeed_NaverEP_SellingIndex_new.txt");
			log.info("네이버 판매지수EP 파일 경로: {}", uploadPath);

			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(uploadPath)), "UTF-8"));
			bw.write(sb.toString());
			bw.flush();
			bw.close();
		}

		return "OK";
	}

	@Override
	public void notify(String result) throws Exception {
		// Do nothing
	}

	/**
	 * EP 타이틀 설정
	 * @param sb - StringBuilder
	 */
	private void setEpTitle(StringBuilder sb) {
		sb.append("id\t").append("sale_count\t").append("sale_price\t").append("order_count\t").append("dt\n");
	}

	/**
	 * EP 정보 설정
	 * @param sb - StringBuilder
	 * @param goodsEp - 상품EP 정보
	 */
	private void setEpInfo(StringBuilder sb, GoodsEp goodsEp) {
		sb.append(goodsEp.getId()).append("\t");
		sb.append(goodsEp.getSaleCount()).append("\t");
		sb.append(goodsEp.getSalePrice()).append("\t");
		sb.append(goodsEp.getOrderCount()).append("\t");
		sb.append(goodsEp.getDt()).append("\n");
	}

}
