#!/sw/bin/perl -w
##################################
# By: Ventz Petkov               #
# Date: 7-01-05                  #
# Convert *.html into Kwiki text #
##################################
use strict;
use LWP::Simple;
use HTML::WikiConverter;
our $wc = new HTML::WikiConverter( dialect => 'Kwiki' );

##################################################
# Let's get Started with an Introduction
sub main() {
    print "#-----------------------------------------#\n";
    print "| Welcome to the HTML -> Kwiki Converteri |\n";
    print "| Please make a selection:                |\n";
    print "| 1. HTML File is on the Web              |\n";
    print "| 2. HTML File is on Hard Drive           |\n";
    print "| 3. EXIT                                 |\n";
    print "#-----------------------------------------#\n";
    print "Choice (enter 1 or 2 or 3): ";
    my $choice = <STDIN>;
    chomp($choice);
    convert($choice); 
}

##################################################
# What has the user selected? Net or Harddisk
sub convert() {
    my $choice = shift;
    if ($choice == 1) {
        # Darn it, we have to pull the file from the net
        print "What's the URL of the file?\n";
        print "(ex: http://www.ex.com/file.html): ";
        my $file_url = <STDIN>; chomp($file_url);
        my $file = get($file_url); 
        # Wahoo, we got it
        my $wiki = $wc->html2wiki( $file ); 
        record($wiki);
        close(FP);
    }
    
    elsif ($choice == 2) {
        # Sweet, let's start reading the file
        print "Where is the file Located?\n";
        print "(ex: /home/user/file.html): ";
        my $file_path = <STDIN>; chomp($file_path);
        my $wiki = $wc->html2wiki( file => $file_path );
        record($wiki);
        close(FP);
    }

    elsif ($choice == 3) {
        # Ok, byebye
        exit();
    }
    
    else {
        # User can't read or type, let's try again
        print "### ERROR! ~ Invalid Choice. Try Again\n";
        main();
    }
}

##################################################
# Write results to a file: kwiki_results.txt
sub record() {
    my $wiki = shift;
    open(FP, ">kwiki_results.txt")
        || die("Cannot write to \"kwiki_results.txt\"");
    print FP $wiki;
}

##################################################
# Start the wheel
main();
