#!/bin/bash
###################################################################### 
#Copyright (C) 2020  Kris Occhipinti
#https://filmsbykris.com

#get voter information

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
###################################################################### 

dir="$HOME/data/voters"
mkdir -p "$dir" || exit 1
cd "$dir" || exit 1

function main(){
  cmd="$(echo -e "Search\nUpdate"|fzf)"
  $cmd
  exit 0
}

function Update(){
  echo "Clearing old data..."
  rm -r "$dir/*"

  echo "Looking for newest Voter's Info..."
  url="$(wget -qO- "http://flvoters.com/downloads.html"|grep 2020|grep download|tail -n1|cut -d\" -f2)"

  echo "Downloading newest Voter's Info"
  url="$(wget -qO- "$url"|grep zip|cut -d\" -f4|tail -n1)"
  wget "$url" -O voter.zip
  unzip voter.zip
  rm voter.zip

  find -name "*.txt"|while read t;do mv "$t" . ;done

  Search
}

function Search(){
  collier="$(ls CLL*.txt)"
  counties="$(ls *.txt)"
  counties="$(echo -e "$collier\n$counties"|fzf --prompt "Select Counties: " -m|sed ':a;N;$!ba;s/\n/ /g')"
  voter="$(cat $counties|fzf)"
  echo "$voter"
  echo "$voter"|cut -d$'\t' -f1,2
  echo "$voter"|cut -d$'\t' -f3,4,5,6|sed 's/\t/ /g'
  address="$(echo "$voter"|cut -d$'\t' -f8,9,10,11,12,13|sed 's/\t/ /g'|sed 's/  / /g'|sed 's/  / /g')"
  echo "$address"
  echo "https://google.com/maps/place/$address"|tr " " "+"

  #cat "$counties"|fzf|sed 's/\t/ /g'|sed 's/  /\n/g'|sed '/^$/d'
}

main