use eframe::egui::{self};
use std::fs::File;

use crate::read_and_write;
use read_and_write::{is_valid_file, save_action, string_translate};

pub struct Omelt {
    file_name: String,
    text: String,
    file: File,
    save_short: KeyboardShortcut,
}

impl Omelt {
    pub fn new(file_name: &str, file: File) -> Self {
        let mut out = Self {
            file_name: file_name.to_owned(),
            text: "".to_owned(),
            file: file,
            save_short: KeyboardShortcut::new(
                egui::Key::S,
                Modifiers {
                    alt: false,
                    ctrl: true,
                    shift: false,
                    mac_cmd: false,
                    command: true,
                },
            ),
        };
        out.update_txt();
        out
    }
    pub fn update_txt(&mut self) {
        if is_valid_file(&mut self.file) {
            self.text = string_translate(&mut self.file);
        } else {
            println!("File is not valid");
        }
    }
}

impl eframe::App for Omelt {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        ctx.input(|i| {
            if self.save_short.matches(i) {
                let _ = save_action(&self.text, &mut self.file);
            }
        });
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.horizontal(|ui| {
                ui.heading(&self.file_name);
                if ui.add(egui::Button::new("Save")).clicked() {
                    let _ = self.file.set_len(0);
                    let _ = save_action(&self.text, &mut self.file);
                }
            });
            egui::ScrollArea::vertical().show(ui, |ui| {
                //let visible_text = self.text.lines().take(100).collect::<Vec<_>>().join("\n");
                ui.add_sized(
                    ui.available_size(),
                    egui::TextEdit::multiline(&mut self.text).lock_focus(true),
                );
            });
        });
    }
}

//---------------------ShortCuts-----------------------

use egui::Modifiers;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct KeyboardShortcut {
    key: egui::Key,
    modifiers: Modifiers,
}

impl KeyboardShortcut {
    fn new(key: egui::Key, modifiers: Modifiers) -> Self {
        Self { key, modifiers }
    }

    fn matches(&self, input: &egui::InputState) -> bool {
        input.key_pressed(self.key) && input.modifiers == self.modifiers
    }
}
