#!/usr/bin/perl

package FCC::mineserv;

# FCC/PTTP Miner v3 (C) 2019 Chaosje, Domero

my $VERSION="3.01";

use strict;
no strict 'refs';
use warnings;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);

$VERSION     = '3.01';
@ISA         = qw(Exporter);
@EXPORT      = qw();
@EXPORT_OK   = qw(startserver);

use Time::HiRes qw(usleep gettimeofday);
use gfio;
use gclient;
use gserv;
use FCC::global;
use FCC::leaf qw(solution);
use FCC::miner;
use FCC::wallet qw(validwallet);
use gthreads;

my $SERV;

1;

sub header {
  print "\n ~~~~~~ FCC / PTTP Coinbase Miner Server v$VERSION ~~~~~~~\n\n";
}

sub tm {
  my @tm=localtime(); my $tms=join(':',map { sprintf('%02d',$_) } reverse @tm[0..2] ); return $tms
}

sub po {
  my ($txt) = @_;
  my $tms=tm();
  print "[$tms] $txt\n"
}

sub startserver {
  header();
  print " * Running WebSocket Wallet Mode\n";
  print " * Starting Server .. ";
  $SERV=gserv::init(\&handleclient);
  $SERV->{server}{port}=5154;
  if ($serv->{error}) {
    print "ERROR $serv->{error}\n\n"; exit
  }
  print "OK\n";
  po(" * Waiting for connections .. ");
}

sub handleclient {
  my ($client,$command,$params) = @_;
  if ($command eq 'connect') {
    po("[Connect] $client->{ip}")
  } elsif ($command eq 'websockets') {
    po("[WebSocket Handshake] $client->{ip} $params");
  }
}

sub readconfig {

}

sub init {
  header();
  print " * Initialisation\n\n";
  my $pttp=0; my $fcc=0;
  if ((-e 'wallet.pttp') || (-e '../wallet.pttp') || (-e '../wallet/wallet.pttp') { $pttp=1 }
  if ((-e 'wallet.fcc') || (-e '../wallet.fcc') || (-e '../wallet/wallet.fcc') { $fcc=1 }
  if ($fcc && $pttp) {
    print "FCC and PTTP wallets found.. Mine 1. FCC 2. PTTP [1] ? ";
    my $ch=<STDIN>; chomp $ch;
    if ($ch eq '2') { setcoin('PTTP') }
  } elsif ($pttp) {
    setcoin('PTTP')
  }
  if (!$fcc && !$pttp) {
    print "No FCC or PTTP wallets found.. Mine 1. FCC 2. PTTP [1] ? ";
    my $ch=<STDIN>; chomp $ch;
    if ($ch eq '2') { setcoin('PTTP') }    
  }
  print " > $COIN selected.\n\n";
  if ($fcc || $pttp) {
    print "Enter a wallet to mine to, or leave blank to select one from an existing wallet file\n < ";
    my $ch=<STDIN>; chomp $ch;
    if (validwallet($ch)) {

    }
  }
}

# EOF FCC / PTTP Coinbase Miner Server v3.1 (C) 2019 Chaosje, Domero