From 70b4b1dc65bfd493088443c20c4670a62c06f317 Mon Sep 17 00:00:00 2001 From: Joe Robinson Date: Fri, 18 Jul 2014 18:27:00 +0100 Subject: Added initial voting functionality --- blavote.go | 51 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 9 deletions(-) (limited to 'blavote.go') diff --git a/blavote.go b/blavote.go index 85e9c5e..a27742a 100644 --- a/blavote.go +++ b/blavote.go @@ -7,23 +7,24 @@ import "github.com/jessevdk/go-flags" import "os" import "io/ioutil" import "strings" +import "strconv" var version string func main() { - version = "0.02" + version = "0.1" //Command line arguments var opts struct { Version bool `short:"v" long:"version" description:"Show program version"` - Add bool `short:"a" long:"add" description:"Add a new poll"` - New bool `short:"n" long:"new" description:"Add a new poll"` + Add string `short:"a" long:"add" description:"Title for a new poll"` + New string `short:"n" long:"new" description:"Title for a new poll"` Username string `short:"u" long:"username" description:"Username of user adding poll"` Args struct { - Title string - PollId int + Rest []string + } `positional-args:"yes"` } @@ -54,13 +55,27 @@ func main() { if (opts.Version) { fmt.Println("v" + version) - } else if (opts.Add || opts.New) { - err := addPoll(db, opts.Args.Title, opts.Args.Rest, opts.Username) + } else if (opts.Add != "") { + fmt.Println(opts.Args.Rest) + + pollId, err := addPoll(db, opts.Add, opts.Args.Rest, opts.Username) + if (err == nil) { + fmt.Print("Poll added with ID ") + fmt.Println(pollId) + } else { + fmt.Println(err) + } + } else if (opts.New != "") { + pollId, err := addPoll(db, opts.New, opts.Args.Rest, opts.Username) if (err == nil) { - fmt.Println("Poll added") + fmt.Print("Poll added with ID ") + fmt.Println(pollId) } else { fmt.Println(err) } + } else { + fmt.Println(opts.Args.Rest) + vote(db, opts.Username, opts.Args.Rest) } @@ -97,5 +112,23 @@ func initTables(db *sqlite3.Conn) { db.Exec("create table options(id integer primary key autoincrement, text text, poll_id int)") db.Exec("create table votes(id integer primary key autoincrement, user_id int, poll_id int, option_id int)") - } + +func vote(db *sqlite3.Conn, nick string, options []string) { + + if pollId, err := strconv.Atoi(options[0]); err == nil { + option := getOptionFromText(db, options[1]) + user := getUserForName(db, nick) + args := sqlite3.NamedArgs{"$a": user.id, "$b": pollId, "$c": option.id} + sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + + err := db.Exec(sql, args) + + if (err != nil ) { + fmt.Print("Failed to vote: ") + fmt.Print(err) + } else { + fmt.Println("Vote added") + } + } +} \ No newline at end of file -- cgit v1.2.3