package com.itsol.quantrivanphong.access.register.bussiness;


import com.itsol.quantrivanphong.access.register.dto.EmailDTO;
import com.itsol.quantrivanphong.access.register.dto.VerifyDTO;
import com.itsol.quantrivanphong.access.register.repository.RegisterRepository;
import com.itsol.quantrivanphong.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.Random;

@Service
public class GeneratePasswordBussiness {

    @Autowired
    private RegisterRepository registerRepository;

    @Autowired
    private EmailBussiness emailBussiness;




    public String getAlphaNumericString(){
        
        // length is bounded by 256 Character 
        byte[] array = new byte[256];
        new Random().nextBytes(array);
        int n = 8;
        String randomString = new String(array, Charset.forName("UTF-8"));

        // Create license StringBuffer to store the result
        StringBuffer pass = new StringBuffer();

        // Append first 20 alphanumeric characters 
        // from the generated random String into the result 
        for (int k = 0; k < randomString.length(); k++) {

            char ch = randomString.charAt(k);

            if (((ch >= 'a' && ch <= 'z')
                    || (ch >= 'A' && ch <= 'Z')
                    || (ch >= '0' && ch <= '9'))
                    && (n > 0)) {

                pass.append(ch);
                n--;
            }
        }
        return pass.toString();
    }


    public String insertPassword(String username){
        String mess;
            Employee employee = registerRepository.findByUsername(username);
            if(employee == null){
                mess = "Không tìm thấy Username";
            }else {
                if(employee.isStatus()) {

                    mess = "Tài khoản đã được kích hoạt từ trước";
                }else {

                    VerifyDTO verifyDTO = new VerifyDTO();
                    verifyDTO.setId(employee.getId());
                    verifyDTO.setPassword(getAlphaNumericString());
                    verifyDTO.setEmailAddress(employee.getEmailAddress());
                    verifyDTO.setStatus(true);
                    registerRepository.insertPassword(verifyDTO.getPassword(),verifyDTO.isStatus(),verifyDTO.getId());
                    EmailDTO emailDTO = new EmailDTO();
                    emailDTO.setSubject("Your Password");
                    emailDTO.setMessage("Your password is: "+verifyDTO.getPassword()+ " You are ready to login!!!!");
                    emailDTO.setRecipientEmail(verifyDTO.getEmailAddress());
                    emailBussiness.sendEmail(emailDTO);
                    mess = "Kích hoạt thành công, kiểm tra email để lấy mật khẩu.";

                }
            }
        return  mess;
    }


}
