package jp.co.jid.fileIO;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

public class Exercises01 {

	public static void main(String[] args) {
		Exercises01 exercises01 = new Exercises01();
		ArrayList<String> inputList = exercises01.fileRead();
		ArrayList<String> outputList = exercises01.editData(inputList);
		exercises01.fileWrite(outputList);
	}

	private ArrayList<String> fileRead() {
		File file = new File(System.getProperty("user.dir") + "\\resource\\input.txt");
		FileReader fr = null;
		try {
			fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BufferedReader br = new BufferedReader(fr);
		ArrayList<String> inputStrList = new ArrayList<String>();
		String lineData;
		try {
			while ((lineData = br.readLine()) != null) {
				inputStrList.add(lineData);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return inputStrList;
	}

	private void fileWrite(ArrayList<String> outputStrList) {
		File file = new File(System.getProperty("user.dir") + "\\resource\\output.txt");
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			for (String lineData : outputStrList) {
				fileWriter.write(lineData);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private ArrayList<String> editData(ArrayList<String> inputDataList) {
		ArrayList<String> outputDataList = new ArrayList<String>();
		for (String inputDataLine : inputDataList) {
			String inputDatas[] = inputDataLine.split(",");

			StringBuffer sb = new StringBuffer();
			sb.append(inputDatas[0]);
			sb.append(",");
			sb.append(inputDatas[1]);
			sb.append(",");
			sb.append(dateAdd(inputDatas[2], inputDatas[3]));
			outputDataList.add(sb.toString());
		}
		return outputDataList;
	}

	private String dateAdd(String str1, String str2) {
		String time[] = str1.split("/");
		LocalDate date = LocalDate.of(
							Integer.valueOf(time[0]).intValue(),
							Integer.valueOf(time[1]).intValue(),
							Integer.valueOf(time[2]).intValue());
		date = date.plusDays(Long.valueOf(str2));
		return DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date);
	}
}
