package cokr.xit.fims.base.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.applib.Hangul;
import cokr.xit.base.code.service.CodeQuery;
import cokr.xit.base.code.service.bean.CodeBean;
import cokr.xit.base.web.ApplicationController;
import cokr.xit.fims.base.Backup;
import cokr.xit.fims.base.service.bean.AdminBean;
import cokr.xit.fims.cmmn.DirectoryStructureToJson;
import cokr.xit.fims.cmmn.DirectoryStructureToJson.Node;
import cokr.xit.fims.crdn.service.ImportService;
import cokr.xit.foundation.data.DataObject;
import cokr.xit.interfaces.smg.service.SmgService;

@Controller
@RequestMapping(name="최고관리자", value="/admin")
public class AdminController extends ApplicationController {
	@Resource(name="adminBean")
	private AdminBean adminBean;
	@Resource(name="codeBean")
	private CodeBean codeBean;
	@Resource(name="smgService")
	private SmgService smgService;
	@Resource(name="importService")
	private ImportService importService;


	@RequestMapping(name="최고관리자 메인",value="/main.do")
	public ModelAndView adminMain(HttpServletResponse hres) {
		if(!"ADMIN00".equals(currentUser().getInstitute())) {
			hres.setStatus(HttpStatus.FORBIDDEN.value());
			return new ModelAndView("jsonView")
				.addObject("message","메뉴 접근 권한이 없습니다.");
		} else {
			return new ModelAndView("fims/admin-main")
				.addObject("pageName","adminMain");
		}
	}

	@RequestMapping(name="배치 수동 실행",value="/executeBatch.do")
	public ModelAndView executeBatch(String batch) {
		switch (batch) {
		case "smgReceive" : {
			smgService.receivePetitions();
			break;
		}
		case "smgSend" : {
			smgService.sendReplies();
			break;
		}
		case "epostSend" : {

			break;
		}
		case "epostReceive" : {

			break;
		}
		default:

		}
		return new ModelAndView("jsonView");
	}

	@RequestMapping(name="업무통보 수동 실행",value="/executeAlert.do")
	public ModelAndView executeAlert(String alertName, String interfaceKey) {
		switch (alertName) {
		case "smgReceive": {
			if(isEmpty(interfaceKey))
				throw new RuntimeException("인터페이스키 없음");

			List<String> interfaceKeys = new ArrayList<String>();
			interfaceKeys.add(interfaceKey);
			importService.createCrdns(interfaceKeys);

			break;
		}
		case "smgSend": break;
		case "epostSend": break;
		case "epostReceive": break;
		default: break;
		}
		return new ModelAndView("jsonView");
	}

	@RequestMapping(name="서버 파일 현황 조회",value="/getFileTree.do")
	public ModelAndView getFileTree() throws Exception {
		ModelAndView mav = new ModelAndView("jsonView");

		File files_folder = new File("files");
		if(!files_folder.exists()) {
			boolean mkdirs = files_folder.mkdirs();
			if(!mkdirs) {
				mav.addObject("tree", null);
				return mav;
			}
		}
		Node tree = DirectoryStructureToJson.getNode(files_folder);
		return mav.addObject("tree", tree);
	}

	@RequestMapping(name="최고관리자 서버 폴더 생성", value="/createDirectory.do")
	public ModelAndView createDirectory(@RequestParam(value="directories[]") String... directories) throws Exception {
		String path = String.join(File.separator, directories);
		File newDir = new File(path);
		boolean saved = newDir.mkdir();

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	@RequestMapping(name="최고관리자 서버 파일 추가", value="/importFile.do")
	public ModelAndView importFile(MultipartFile newFile, @RequestParam(value="directories[]") String... directories) throws Exception {
		String path = String.join(File.separator, directories);
		path = path + File.separator + newFile.getOriginalFilename();

		File file = new File(path);
		newFile.transferTo(file);
		boolean saved = file.exists();

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	@RequestMapping(name="최고관리자 서버 파일 내용 보기", value="/getFileText.do")
	public ModelAndView getFileText(@RequestParam(value="directories[]") String... directories) throws Exception {
		String fileCn = "";
		StringBuilder sb = new StringBuilder();

		String path = String.join(File.separator, directories);

		int inputData = 0;
		try {
			Hangul hangul = new Hangul(3);
			String detect = hangul.encodingDetect(path);
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path),Charset.forName(detect)));

			while ((inputData = br.read()) != -1) {
				sb.append((char)inputData) ;
			}

			fileCn = sb.toString();

			br.close();
		} catch (Exception e) {

		}

		return new ModelAndView("jsonView")
			.addObject("fileCn", fileCn);
	}

	@GetMapping(name="시군구 추가/삭제 메인", value="/sggAddDelInfo.do")
	public ModelAndView sggAddDelMain() {
		return new ModelAndView("fims/admin-sggAddDel-info")
			.addObject("pageName","adminSggAddDel");
	}

	@GetMapping(name="백업 테이블 및 실사용 테이블 자료 조회", value="/sggBackup/list.do")
	public ModelAndView getBackupList(String backupTable, String originalTable, String pkName) {
		List<DataObject> originalDataList = adminBean.getAllList(originalTable, pkName);
		List<DataObject> backupDataList = adminBean.getAllList(backupTable, originalTable, pkName);

		return new ModelAndView("jsonView")
			.addObject("originalDataList", originalDataList)
			.addObject("backupDataList", backupDataList);
	}

	@PostMapping(name="백업 테이블 자료를 사용 테이블로 복사", value="/sggBackup/activate.do")
	public ModelAndView add(Backup backup) {
		boolean saved = adminBean.activate(backup);

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	@PostMapping(name="사용 테이블 자료 삭제 및 백업", value="/sggBackup/deactivate.do")
	public ModelAndView del(Backup backup) {
		boolean saved = adminBean.deactivate(backup);

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	@GetMapping(name="시군구 설정 복사 메인", value="/copySggStngInfo.do")
	public ModelAndView copySggStngMain() {
		CodeQuery cq = new CodeQuery();
		cq.setGroupIDs("FIM054");
		List<DataObject> taskSeCdList = codeBean.getCodeList(cq);
		List<DataObject> sggList = adminBean.getAllList("TB_SGG", "SGG_NM");

		return new ModelAndView("fims/admin-copySggStng-info")
			.addObject("pageName","admin-copySggStng")
			.addObject("taskSeCdList", taskSeCdList)
			.addObject("sggList", sggList);
	}

	@GetMapping(name="시군구 설정 복사", value="/copySggStng.do")
	public ModelAndView copy(String taskSeCd, String srcSgg, String trgtSgg) {
		boolean saved = adminBean.copySggStng(taskSeCd, srcSgg, trgtSgg);

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}
}