package com.hmsoft.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSON;
import com.hmsoft.common.FileConst;
import com.hmsoft.model.CoursePlan;
import com.hmsoft.model.SelectedCourse;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * 
 * @author zq
 *
 */
public class CoursePlanDataUtil {

	private CoursePlanDataUtil() {
		
	}
	
	//
	public static List<String> getPublishedBatchNoList() {
		final List<String> batchNoList = new ArrayList<String>();
		final File file = new File(FileConst.DATA_BASE);
		if (file.exists()) {
			File[] fs = file.listFiles();
			for (File f : fs) {
				batchNoList.add(f.getName().split("-")[1]);
			}
		}
		return batchNoList;
	}
	
	//从指定文件中加载征集计划.
	public static ObservableList<CoursePlan> loadCoursePlanData(final String batchNo) {
		final ObservableList<CoursePlan> dataList = FXCollections.observableArrayList();
		final File file = new File(FileConst.COURSEPLAN_FINAL_PATH + "-" + batchNo);
		try {
			if (file.exists()) {
				final List<String> list = IOUtils.readLines(new FileInputStream(file), Charset.forName("UTF-8"));
				for (String str : list) {
					CoursePlan courseplan = JSON.parseObject(str, CoursePlan.class);
					dataList.add(courseplan);
				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataList;
	}
	
	//导入写到文件中.
	public static void writeCoursePlan(final List<SelectedCourse> coursePlanList, final String batchNo) {
		PrintWriter writer = null;
		File destFile = new File(FileConst.COURSEPLAN_FINAL_PATH + "-" + batchNo);
		if (!destFile.exists()) {
			try {
				destFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			writer = new PrintWriter(destFile, "UTF-8");
			for (SelectedCourse obj : coursePlanList) {
				String json = JSON.toJSONString(obj);
				writer.write(json + FileConst.FILE_NEWLINE);
			}
		} catch (FileNotFoundException | UnsupportedEncodingException e) {
			System.err.println("------------error---" + e.getMessage());			
			e.printStackTrace();
		} finally {
			if (writer != null) {
				writer.flush();
				writer.close();
			}
		}
	}
	
}
