package com.dbs.mplus.controller.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dbs.mplus.exception.admin.AdminControllerException;
import com.dbs.mplus.framework.FrameworkConstants.MP_ATTR_TYPE;
import com.dbs.mplus.framework.api.executor.ApiExecuteDelegator;
import com.dbs.mplus.framework.exception.MPlusServiceException;
import com.dbs.mplus.framework.service.admin.attr.AttrService;
import com.dbs.mplus.framework.service.admin.attr.ExtraAttrService;
import com.dbs.mplus.framework.service.admin.attr.repository.dao.Attr;
import com.dbs.mplus.framework.service.admin.attr.repository.dao.AttrType;
import com.dbs.mplus.service.MPlusConfigureService;

/**
 * 속성 관리 Controller (권한 속성, 추가 속성 관리, 사용자 속성등에서 사용될수 있다.)
 * @author heesungkim
 *
 */
@Controller
@RequestMapping("/admin/attr")
public class AttrController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	@Qualifier("apiExecuteDelegator")
    private ApiExecuteDelegator executor;
	@Autowired 
	private MPlusConfigureService configureService; 
	@Autowired
	private AttrService attrService;
	@Autowired
	private ExtraAttrService extraAttrService;
	
	@RequestMapping(value = "/view.page", method = RequestMethod.GET)
	public Model view(Model model) throws AdminControllerException {
		try { 
			model.addAttribute("defaultLanguage", this.configureService.getI18nDefault());
			model.addAttribute("supportedLanguages", this.configureService.getI18nSupported().split(","));
		}
		catch(final Exception ex) {
			this.logger.error("", ex);
			throw new AdminControllerException(ex); 
		}
		
		return model;
	}
	
	@RequestMapping(value = "/getAttrTypeList.json", method = RequestMethod.POST) 
	@ResponseBody
	public Map<String, Object> getAttrTypeList() throws AdminControllerException {
		
		try { 
			Map<String, Object> resultMap = new HashMap<String, Object>();
			
			// 속성 타입 가져오기 MP_ATTR_TYPE
			MP_ATTR_TYPE[] mpAttrTypeList = MP_ATTR_TYPE.values();
						
			List<AttrType> attrTypeList = new ArrayList<AttrType>();
			
			for( int i = 0; i < mpAttrTypeList.length; i++) {
				AttrType attrType = new AttrType();
				attrType.setAttrTypeSeq((long) i);
				attrType.setAttrType(mpAttrTypeList[i].getAttrType());
				attrType.setAttrTypeName(mpAttrTypeList[i].getAttrTypeName());
				attrTypeList.add(attrType);
			}
			
			resultMap.put("attrTypeList", attrTypeList);
			
			return resultMap;
			
		} catch(final MPlusServiceException ex) {
			throw new AdminControllerException(ex); 
		}
	}
	

	@RequestMapping(value = "/getAttrList.json", method = RequestMethod.POST) 
	@ResponseBody
	public Map<String, Object> getAttrTypeList(@RequestBody AttrType attrType) throws AdminControllerException {
		
		try { 
			Map<String, Object> resultMap = new HashMap<String, Object>();
			
			if(MP_ATTR_TYPE.EXTRA.getAttrType().equals(attrType.getAttrType())) {
				resultMap.put("extraAttrList", this.extraAttrService.getList());
			} else {
				resultMap.put("attrList", this.attrService.findListByAttrType(attrType.getAttrType()));
				/*// 속성 타입이 duty이면
				// duty 타입의 속성이 종속된 work 타입을 가졌을 가능성에 대한 고려?
				// 다른 종속관계가 발생할 가능성은?
				if(attrType.getAttrTypeId().equals("duty")) {
					List<Attr> attrList = this.attrService.findListByAttrType(attrType2.getAttrType());
					for (Attr attr : attrList) {
						List<Attr> attrList2 = this.attrService.findListByUpperAttr(attr.getAttrType(), attr.getAttrId());
						resultMap.put(attr.getAttrId(), attrList2);
					}
				}*/
			}
			
			return resultMap;
			
		} catch(final MPlusServiceException ex) {
			this.logger.error("추가 속성 가져오기 실패", ex);
			throw new AdminControllerException(ex); 
		}
	}
	
	@RequestMapping(value = "/save.json", method = RequestMethod.POST) 
	@ResponseBody
	public Attr save(@RequestBody Attr attr) throws AdminControllerException {
		try { 
			 this.attrService.save(attr);
		} catch(final MPlusServiceException ex) {
			this.logger.error("속성 저장 실패", ex);
			throw new AdminControllerException(ex); 
		}
		
		return attr;
	}
	
	@RequestMapping(value = "/remove.json", method = RequestMethod.POST) 
	@ResponseBody
	public void remove(@RequestBody Attr attr) throws AdminControllerException {
		try { 
			if( attrService.getCountUserAttrByAttrId(attr.getAttrType(), attr.getAttrId()) > 0) {
				throw new AdminControllerException("해당 속성을 가진 사용자가 있습니다. " + attr.getAttrId());
			} else {
				this.attrService.remove(attr);
			}
		} catch(final MPlusServiceException ex) {
			this.logger.error("속성 삭제 실패", ex);
			throw new AdminControllerException(ex); 
		}
	}
}
