/**
 *
 */
package common;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author user
 *
 */
public class Maintenance extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String contentType = "text/html; charset=UTF-8";
		response.setContentType(contentType);

		String envPath = getServletContext().getRealPath("/conf/env.ini");
		Environment env = Environment.getEnvironment();
		env.init(envPath);

		HttpSession session = request.getSession(false);

		String in_userid = (String)session.getAttribute("userid");
		if ( in_userid.equals("") ) {
			return;
		}

		String in_option = request.getParameter("option");
		if ( in_option.equals("") ) {
			return;
		}

		if ( in_option.equals("setupAccountGroup") ) {
			setupAccountGroup(in_userid);
		}
	}

	//勘定科目分類初期設定
	private void setupAccountGroup(String in_userid) {

		String path = getServletContext().getRealPath("/conf/account_group.ini");

		//勘定科目分類初期設定ファイル読み込み
		ArrayList<String[]> lines = new ArrayList<String[]>();
		FileReader in = null;
		BufferedReader br = null;
		try {
			in = new FileReader(path);
			br = new BufferedReader(in);
			String line = "";
			while ((line = br.readLine()) != null) {
				if (line.equals("")) {
					continue;
				}
				lines.add(line.split("\t"));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		AccountGroup accountGroup = new AccountGroup();

		//勘定科目分類テーブル初期化
		int resultDelete = 0;
		resultDelete = accountGroup.delete("");
		if ( resultDelete < 0 ) {
			return;
		}

		//勘定科目分類登録
		ArrayList<String> attributes = new ArrayList<String>();
		ArrayList<String> values = new ArrayList<String>();
		String resultCreate = "";

		attributes.clear();
		attributes.add("account_group_number");
		attributes.add("super_number");
		attributes.add("name");
		attributes.add("dc");
		attributes.add("bp");
		attributes.add("create_person");
		attributes.add("modify_person");

		for( int ii = 0; ii < lines.size(); ++ii ) {
			String[] attrs = lines.get(ii);
			values.clear();
			values.add(attrs[0]);
			values.add(attrs[1]);
			values.add(attrs[2]);
			values.add(attrs[3]);
			values.add(attrs[4]);
			values.add(in_userid);
			values.add(in_userid);
			resultCreate = accountGroup.create(attributes, values);
			if ( resultCreate.equals("") ) {
				return;
			}
		}
	}
}
