package com.lightinit.hsdatashow.common;

import com.lightinit.hsdatashow.entity.Securekey;
import com.lightinit.hsdatashow.service.ISecureKeyService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Lantinit on 2018/2/1.
 */
@Component
public class SecureCardUtilsPro {
    @Autowired
    private ISecureKeyService secureKeyService;

    public boolean verification(HttpSession session,String token,String cardno,long synctime){
        String capText=session.getAttribute("SECUREKEY_SESSION_KEY")!=null?session.getAttribute("SECUREKEY_SESSION_KEY").toString():"";
        if(StringUtils.isEmpty(capText)){
            return false;
        }
        String realToken="";
        String[]TokenArray=capText.split(":::");
        for (String item:TokenArray) {
            String secretStr=item.substring(1)+":::"+cardno+":::"+synctime+":::"+item.substring(0,1);
            try {
                realToken+=OneTimePasswordAlgorithm.generateOTP(secretStr.getBytes(), 0, 2, false, -1);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
        }
        if(realToken.equalsIgnoreCase(token)==false){
            return false;
        }
        session.removeAttribute("SECUREKEY_SESSION_KEY");
        return true;
    }

    public boolean verification(HttpSession session,String token,String username){
        Securekey securekey= secureKeyService.QueryOne(username);
        if(securekey==null){
            return false;
        }
        SimpleDateFormat syncDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date syncDate= syncDateFormat.parse(syncDateFormat.format(securekey.getSyncdatetime()));
            return verification(session,token,securekey.getSecurekey(),syncDate.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
    public boolean verification(HttpSession session,String token){
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser==null){
            return false;
        }
        return verification(session,token,currentUser.getPrincipal().toString());
    }
}
