#!/usr/bin/env perl
use strict;
use warnings;
use Curses;
use Time::Stopwatch;
srand;

my @texty = ("The name curses is a pun on cursor optimization. Sometimes it is incorrectly stated that curses was used by the vi editor. In fact the code in curses that optimizes moving the cursor from one place on the screen to another was borrowed from vi, which predated curses. (Wikipedia)");
my $text;   #vylosovany text
my $key;
my($y, $x, $w_y, $w_x);
my $prvni_radek = 3;
my $intro = "RYCHLOST PSANI";
my $verze = "verze 1.0";
my $pozice_v_textu = 0;
my $pozice_x = 0;
my $pozice_y = $prvni_radek+1;

initscr;
END{endwin;}
curs_set(0);
noecho();

#intro
getmaxyx(stdscr, $y, $x);
my $vyska_okna=7;
my $sirka_okna=30;
refresh;
my $w = newwin($vyska_okna, $sirka_okna, ($y-$vyska_okna)/2, ($x-$sirka_okna)/2);
box($w, 0, 0);
getmaxyx($w, $w_y, $w_x);
addstr($w, 2, ($w_x - length($intro))/2, $intro);
addstr($w, 4, ($w_x - length($verze))/2, $verze);
refresh($w);

timeout(2000);
getch;
notimeout(stdscr, 1);
delwin($w);

#vyprazdnime obrazovku
clear;

#zobrazi uvodni obrazovku
my $s = "Stisknete ENTER pro pokracovani";
addstr($s);
$text = $texty[int(rand($#texty+1))];
$text =~ tr/\n/ /;
for(my($radek,$pozice)=($prvni_radek,0); $pozice<length($text); $pozice+=$x, $radek+=3){
    move($radek, 0);
    addstr(substr($text, $pozice, $x));
}
while(($key=getch()) ne "\n"){}

delete_string(0, 0, length($s));

#presuneme kurzor
move($pozice_y, $pozice_x);
curs_set(1);

#zacneme merit cas
tie my $timer, "Time::Stopwatch";

#hlavni cyklus programu - uzivatel pise a program vyhodnocuje
while($key = getch){
    #napsal spravny znak
    if($key eq substr($text, $pozice_v_textu, 1)){
        addstr($key);
        $pozice_v_textu++;
        $pozice_y = $prvni_radek+1+3*int($pozice_v_textu/$x);
        $pozice_x = $pozice_v_textu % $x;
        move($pozice_y, $pozice_x);
    #udelal chybu
    }else{
        move($pozice_y, $pozice_x);
        addstr(" ");
        move($pozice_y, $pozice_x);
    }

    #konec
    if(length($text) == $pozice_v_textu){
        move(0, 0);
        addstr("HOTOVO!");
        move(1, 0);
        addstr(sprintf("Pocet znaku: %4d   Vas cas: %5.2fs   Znaku/sec: %5.2f", length($text), $timer, length($text)/$timer));
        last;
    }
}

refresh;
while(getch() ne "\n"){;}


sub delete_string {
    my($y, $x, $kolik) = @_;
    my($puv_x, $puv_y);
    getyx($puv_y, $puv_x);
    move($y, $x);
    addstr(" " x $kolik);
    move($puv_y, $puv_x);
}