use std::fs;

use rand::thread_rng;
use rsa::Pkcs1v15Encrypt;
use rsa::{RsaPrivateKey, RsaPublicKey, pkcs8::DecodePublicKey};
use rsa::pkcs8::{LineEnding, EncodePrivateKey, DecodePrivateKey, };
pub fn get_priv_key()->RsaPrivateKey{
    let priv_key = RsaPrivateKey::read_pkcs8_der_file("/etc/etapkilit/etapkilit.der");
    if let Ok(p_key) = priv_key{
        println!("priv bulundu");
        return p_key
    }
    let mut rng = rand::thread_rng();
    let priv_key = RsaPrivateKey::new(&mut rng, 2048).unwrap();
    priv_key.write_pkcs8_der_file("/etc/etapkilit/etapkilit.der").unwrap();
    priv_key
}

fn get_priv_from_file()->Result<RsaPrivateKey, rsa::pkcs8::Error>{
    RsaPrivateKey::read_pkcs8_der_file("/etc/etapkilit/etapkilit.der")
}

pub fn create_password(priv_key: rsa::RsaPrivateKey){
    let mut passwd1 = String::new();
    println!("Şifreyi giriniz");
    std::io::stdin().read_line(&mut passwd1).unwrap();
    passwd1.trim();
    let mut passwd2 = String::new();
    println!("Şifreyi giriniz(tekrar)");
    std::io::stdin().read_line(&mut passwd2).unwrap();
    passwd2.trim();
    if passwd1 == passwd2{
        let pub_key = RsaPublicKey::from(priv_key);
        let dec_data = pub_key.encrypt(&mut thread_rng(), Pkcs1v15Encrypt, &passwd1[..].as_bytes());
        write_pub_key(dec_data.unwrap());
    };
}
pub fn get_passwd_key()->Vec<u8>{
    fs::read("/etc/etapkilit/password.key").unwrap()
}
fn write_pub_key(passwd: Vec<u8>){
    std::fs::write("/etc/etapkilit/password.key", passwd);
}