
package nlib.user.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import egovframework.com.ext.oauth.service.OAuthUniversalUser;
import egovframework.rte.fdl.cryptography.EgovPasswordEncoder;
import nlib.cmm.crypto.AriaCrypto;
import nlib.restful.service.DataApiReqVO;
import nlib.restful.service.DataApiResVO;
import nlib.user.service.MemberService;
import nlib.user.service.NlibLoginVO;
import nlib.user.service.NlibSmsVO;
import nlib.util.StringUtil;

@Service("memberService")
public class MemberServiceImpl implements MemberService
{
	@Resource(name="memberDAO")
	private MemberDAO memberDAO;
	
	@Resource(name = "egovEnvPasswordEncoderService")
    EgovPasswordEncoder egovPasswordEncoder;
	
	@Resource(name = "ariaCrypto")
    AriaCrypto ariaCrypto;

	public DataApiResVO selectMemberJoiningInfo(DataApiReqVO reqVO)  {
		return null;
	}

	public DataApiResVO certificateMember(DataApiReqVO reqVO)  {
		return null;
	}

	public void insertMemberInfo(NlibLoginVO vo) throws Exception {
		//회원정보 암호화
		String encodedText=null;
		encodedText = egovPasswordEncoder.encryptPassword(vo.getLoginUserId()+vo.getPassword());
		vo.setPassword(encodedText);
		vo.encodePrivateInfo();
		//회원가입 정보
		memberDAO.insertMemberInfo(vo);
		
	}
	
	public DataApiResVO sendEmailForMemberJoining(DataApiReqVO reqVO)  {
		return null;
	}

	public DataApiResVO searchId(DataApiReqVO reqVO)  {
		return null;
	}

	public DataApiResVO initPassword(DataApiReqVO reqVO)  {
		return null;
	}

	public void changePassword(NlibLoginVO vo) throws Exception  {
		memberDAO.changePassword(vo);
	}

	public DataApiResVO selectMemberInfo(DataApiReqVO reqVO)  {
		return null;
	}

	public DataApiResVO updateMemberInfo(DataApiReqVO reqVO)  {
		return null;
	}

	public DataApiResVO leaveMember(DataApiReqVO reqVO)  {
		return null;
	}

	//핸드폰 인증번호 난수 생성
	/**
     * 전달된 파라미터에 맞게 난수를 생성한다
     * @param len : 생성할 난수의 길이
     * @param dupCd : 중복 허용 여부 (1: 중복허용, 2:중복제거)
     * 
     */
    public String numberGen(int len, int dupCd ) {
        
        Random rand = new Random();
        String numStr = ""; //난수가 저장될 변수
        
        for(int i=0;i<len;i++) {
            
            //0~9 까지 난수 생성
            String ran = Integer.toString(rand.nextInt(10));
            
            if(dupCd==1) {
                //중복 허용시 numStr에 append
                numStr += ran;
            }else if(dupCd==2) {
                //중복을 허용하지 않을시 중복된 값이 있는지 검사한다
                if(!numStr.contains(ran)) {
                    //중복된 값이 없으면 numStr에 append
                    numStr += ran;
                }else {
                    //생성된 난수가 중복되면 루틴을 다시 실행한다
                    i-=1;
                }
            }
        }
        return numStr;
    }

    /**
     * 초기화 비밀번호 랜덤생성
     */
    public String createInitPwd() {
    	// 비밀번호 자리수
        int pwLength=8;
        
        String dummyPW="";
        List<String> dummylist=new ArrayList<String>();
        
        // 대문자사용 1
        int useU = 1;
        String upperStr="";
        
        // 소문자 사용 1
        int useL = 1;
        String lowerStr="";
        
        // 숫자 사용 1
        int useN = 1;
        String ranNumberStr="";
        
        // 특수문자 사용 1
        int useS = 1;
        String ranSkeyStr="";

        // 사용할 특수문자
        String specialKey="!=#$+@%*";

        // 제외시킬 대,소문자(비슷하게 생긴것들)
        String exceptionKey="IOiol";

        char upperChar;
        char lowerChar;
        char ranSkey;
        int startSkey;
        int ranNumber;
        int whileNum = 0;
        boolean whileFlag = true;
        
        do {
        int loopNum=(int)(Math.random()*4);
        // 대문자생성
        if((whileFlag && upperStr.equals("1")) || (!whileFlag && useU == 1 && loopNum == 0)){
             do {
                  upperChar = (char)(Math.random() * 26 + 65);
                  upperStr=String.valueOf(upperChar);
             } while (exceptionKey.indexOf(upperStr)!=-1);
             dummylist.add(upperStr);
             whileNum++;
        }
        
   // 소문자생성
        if((whileFlag && lowerStr.equals("1")) || (!whileFlag && useL == 1 && loopNum == 1)){
             do {
                  lowerChar = (char)(Math.random() * 26 + 97);
                  lowerStr=String.valueOf(lowerChar);
             } while (exceptionKey.indexOf(lowerStr)!=-1);
             dummylist.add(lowerStr);
             whileNum++;
        }
        
   // 숫자생성(숫자 0,1 제외)
        if((whileFlag && ranNumberStr.equals("1")) || (!whileFlag && useN == 1 && loopNum == 2)){
	        ranNumber=(int)(Math.random() * 8 + 2);
	        ranNumberStr=String.valueOf(ranNumber);
	        dummylist.add(ranNumberStr);
	        whileNum++;
        }

   // 특수문자생성
        if((whileFlag && ranSkeyStr.equals("1")) || (!whileFlag && useS == 1 && loopNum == 3)){
        	startSkey=(int)(Math.random()* (specialKey.length()-1))+1;
        	ranSkey=specialKey.charAt(startSkey);
        	ranSkeyStr=String.valueOf(ranSkey);
        	dummylist.add(ranSkeyStr);
        	whileNum++;
        }
        whileFlag = false;
        } while (whileNum<pwLength);
   // 섞기
       Collections.shuffle(dummylist); 
       for (String string : dummylist) { 
       dummyPW+=string;
       }
       return dummyPW;
    }

	public NlibLoginVO selectAlreadySignUpId(OAuthUniversalUser oauthUser) throws Exception {
		//이메일 암호화
		oauthUser.setSnsEmail(ariaCrypto.encode(oauthUser.getSnsUserId()));
		return memberDAO.selectAlreadySignUpId(oauthUser);
	}

	public void insertMemberSns(OAuthUniversalUser oauthUser) {
		//사용자 데이터 암호화
		if(!(StringUtil.getString(oauthUser.getSnsBirthday(),"") == ""))
			oauthUser.setSnsBirthday(ariaCrypto.encode(oauthUser.getSnsBirthday()));
		if(!(StringUtil.getString(oauthUser.getSnsEmail(),"") == ""))
			oauthUser.setSnsEmail(ariaCrypto.encode(oauthUser.getSnsEmail()));
		if(!(StringUtil.getString(oauthUser.getSnsMobileNo(),"") == ""))
			oauthUser.setSnsMobileNo(ariaCrypto.encode(oauthUser.getSnsMobileNo()));
		memberDAO.insertMemberSns(oauthUser);
	}

	public List<NlibLoginVO> selectAlreadySignUpMobile(NlibLoginVO loginVO) throws Exception {
			loginVO.setMobileNo(ariaCrypto.encode(loginVO.getMobileNo()));
		return memberDAO.selectAlreadySignUpMobile(loginVO);
	}

	public int selectSnsIdCount(OAuthUniversalUser oauthUser) {
		return memberDAO.selectSnsIdCount(oauthUser);
	}

	public void deleteMembership(NlibLoginVO loginVO) throws Exception {
		memberDAO.deleteMembership(loginVO);
	}

	public void sendSms(NlibSmsVO smsVO) throws Exception {
		memberDAO.sendSms(smsVO);
	}

}