package com.passwordprotector.controller;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.util.logging.Logger;

import javax.swing.JOptionPane;

import com.passwordprotector.Main;
import com.passwordprotector.model.LoginModel;
import com.passwordprotector.utils.EncryptionDecryption;
import com.passwordprotector.utils.FileOperation;


public class LoginController{
	private LoginModel loginModel;
	private static Logger log = Logger.getLogger(LoginController.class.getName());
	public LoginController(LoginModel loginModel) {
		super();
		this.loginModel = loginModel;
	}
	public ItemListener login(){
		log.info("login()");
		return new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
					String username = loginModel.getUserName();
					String password = loginModel.getPassword();
					EncryptionDecryption encryption = new EncryptionDecryption();				
						String realUsername = getRealUserName(encryption);
						String realPassword = getRealPassword(encryption);
						if (!realUsername.equals(username)||!realPassword.equals(password)) {
							loginModel.setMatches(false);
						}
						else if (realUsername.equals(username)
								&& realPassword.equals(password)) {
							loginModel.setMatches(true);
						}	
				
			}
		};
	}
	public ItemListener exit(){
		log.info("exit()");
		return new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent exit) {
				// TODO Auto-generated method stub
				loginModel.setExiting(true);
			}
		};
	}
	private String getRealUserName(EncryptionDecryption encryptionDecryption){
		log.info("getRealUserName()");
		FileOperation usernameFile = new FileOperation("Username.txt");
		try {
			String userNameFromFile = usernameFile.readTextFile();
			encryptionDecryption.decryptData(userNameFromFile.toCharArray());
			String realUsername = String.valueOf(encryptionDecryption.getDecrypted());
			usernameFile.Readerclose();
			return realUsername;
		}
		catch (IOException exception) {
			// TODO Auto-generated catch block
			exception.printStackTrace();
		}
		catch (Throwable d) {
			d.printStackTrace();
		}
		return null;

	}
	private String getRealPassword(EncryptionDecryption encryptionDecryption){
		log.info("getRealPassword()");
		FileOperation passwordFile = new FileOperation("password.txt");
		try {
			String passwordFromFile = passwordFile.readTextFile();
			encryptionDecryption.decryptData(passwordFromFile.toCharArray());
			String realPassword = String.valueOf(encryptionDecryption.getDecrypted());
			passwordFile.Readerclose();
			return realPassword;
		}
		catch (IOException exception) {
			// TODO Auto-generated catch block
			exception.printStackTrace();
		}
		catch (Throwable d) {
			d.printStackTrace();
		}
		return null;

	}
	
}
