package kr.co.kihyun.beans.totsys.report;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;

import kr.co.kihyun.beans.entity.AssignType;
import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.MoumiEntity;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportType;
import kr.co.kihyun.beans.entity.TotTable;
import kr.co.kihyun.beans.entity.util.QueryImpl;
import kr.co.kihyun.db.CommonDBManager;
import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.lang.MString;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReportUpdate extends DBManager {
	private static final Logger LOG = LoggerFactory.getLogger(ReportUpdate.class);

	private ResultSet rs = null;

	public int deptUserUpdate(PersistenceManager pm, TotDoc totDoc, String[] insertDeptList)
			throws Exception {
		int succNum = 0;
		succNum = allReportsDelTypeTrueConvert(pm, totDoc);
		succNum = deptUserInsert(pm, totDoc, totDoc.getTotTables().iterator().next(), insertDeptList);
		return succNum;
	}

	// FIXME: remove me
	public int deptUserInsert(PersistenceManager pm, TotDoc totDoc, TotTable totTable, String[] deptIDList)
			throws Exception {
		int succNum = 0;

		TotReport totReport = null;
		List<TotReport> totReportDepts = null;
		QueryImpl q = null;
		try {
			q = new QueryImpl(pm, TotReport.class);
			q.setFilter("totDoc == tot_doc && assignType == AssignType.ASSIGN_TO_DEPT");
			//q.setFilter("assignType == AssignType.ASSIGN_TO_DEPT");
			q.declareImports("import kr.co.kihyun.beans.entity.*");
			q.declareParameters("TotDoc tot_doc");
                        //v2. 6.SQL 삽입 : DO형식이므로 해결책에 따른 prepare SQL 문으로 변경할 수 없음
			totReportDepts = (List<TotReport>) q.execute(totDoc);
                        //===============
			int currReportDeptCount = totReportDepts.size();

			Long id = null;
			boolean isDeptAlreadyExist = false;

			LOG.debug("totReportDepts.size() - {}", totReportDepts.size());
			LOG.debug("deptIDList.length : {}", deptIDList.length);
			LOG.debug("deptIDList : {}", deptIDList);
			if (deptIDList != null) {
				LOG.debug("deptIDList is not null");
				for (int i = 0; i < deptIDList.length; i++) {
					LOG.debug("deptIDList[{}]: {}", i, deptIDList[i]);
					if (deptIDList.length == 1 && MString.isNull(deptIDList[0]))
						break;

					for (int j = 0; j < currReportDeptCount; j++) {
						LOG.debug("deptIDList[" + i + "] - {} totReportDepts.get(" + j + ") - {}", deptIDList[i], totReportDepts.get(j).getDept(pm).getId());
						if (deptIDList[i].equals(totReportDepts.get(j).getDept(pm).getId())) {
                                           		isDeptAlreadyExist = true;
                                                       	break;
						} else {
                                                      	isDeptAlreadyExist = false;
                                                        break;
						}
					}

					if (isDeptAlreadyExist) {
                        id = getID(totDoc.getId(), deptIDList[i], null);
						totReport = pm.getObjectById(TotReport.class, id);
						totReport.setDeleted("N");
						totReport.setType(TotReportType.REPORT);
						totReport.setAssignType(AssignType.ASSIGN_TO_DEPT);
					} else {
                        MDept dept = pm.getObjectById(MDept.class, deptIDList[i]);
						totReport = new TotReport(totDoc, dept);
						totReport.setId(getDocID_Sequence());
						totReport.setTableNum(totTable.getNum());
						totReport.setAssignType(AssignType.ASSIGN_TO_DEPT);
					}
					pm.makePersistent(totReport);
					succNum = 1;
				}
			}
			return succNum;
		} catch (Exception ex) {
			LOG.debug("totReport :{}", totReport);
			LOG.error(
					"failed to regist report. del_type {}, recog {}, prss {}, id {}, appro {}, table_num {}, doc_id {}, type {}",
					new Object[] { totReport.isDeleted(), totReport.getRecog(), totReport.getProcess(),
							totReport.getId(), totReport.getAppro(), totReport.getTableNum(), totReport.getTotDoc(),
							totReport.getType() });
			throw ex;
		}
	}

	private int allReportsDelTypeTrueConvert(PersistenceManager pm, TotDoc totDoc) {
		try {
			Set<TotReport> reports = totDoc.getTotReports();
			for (TotReport report : reports)
				report.setDeleted("Y");
			// pm.makePersistentAll(reports.toArray());
			return 1;
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	public Long getID(Long docID, String deptID, String userID) {
		StringBuilder sql = new StringBuilder(120);

		Long id = null;
		ArrayList<Object> paramList = new ArrayList<Object>();

		try {
			if (userID == null) {
				sql.append("select id from ").append(MoumiEntity.getTableName(TotReport.class))
						.append(" where doc_id=? and dept_id=?");
				paramList.add(docID);
				paramList.add(deptID);
			} else {
				sql.append("select id from ").append(MoumiEntity.getTableName(TotReport.class))
						.append(" where doc_id=? and dept_id=? and user_id=?");
				paramList.add(docID);
				paramList.add(deptID);
				paramList.add(userID);
			}

			rs = execQuery(sql.toString(), paramList.toArray());
			if (rs.next()) {
				id = rs.getLong(1);
			}
			return id;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	private long getDocID_Sequence(){
		CommonDBManager cdb = new CommonDBManager();
		ResultSet rs = null;
		long seqId = 0L;
		try{
			rs = cdb.execQuery("SELECT SQ_MOUMI.NEXTVAL AS SEQ_MOUMI FROM DUAL");
			if(rs.next()){
				seqId = rs.getLong("SEQ_MOUMI");
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(null != rs)
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			cdb.execClose();
			return seqId;
		}

	}
}
