package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {

	directory, err := os.Getwd()
	Error(err)

	fmt.Printf("What is the name of the file: ")
	reader := bufio.NewReader(os.Stdin)
	input, err := reader.ReadString('\n')
	Error(err)

	input = strings.TrimSpace(input)
	file, err := os.Open(input)
	Error(err)
	var upcs []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		upcs = append(upcs, scanner.Text())
	}
	err = file.Close()
	Error(err)
	if scanner.Err() != nil {
		fmt.Println(scanner.Err())
	}

	var gtins []string

	for _, upc := range upcs {

		upcLength := len(upc)

		// Check Digit Formula
		// Take all the digits in odd positions, add them and multiply by three
		// Take all the digits in even positions (except for the last one) and add to the number you got above
		// Divide that number by 10 and take the remainder
		// If the remainder is not 0, subtract it from 10

		oddNumber := 0
		evenNumber := 0
		var remainder int

		for i, num := range upc {
			if i%2 == 0 {
				oddString, err := strconv.Atoi(string(num))
				Error(err)
				oddNumber += oddString
			} else {
				if upcLength-1 > i {
					evenString, err := strconv.Atoi(string(num))
					Error(err)
					evenNumber += evenString
				}
			}
		}

		oddNumber = oddNumber * 3
		remainder = (oddNumber + evenNumber) % 10
		if remainder != 0 {
			remainder = 10 - remainder
		}
		remainderString := strconv.Itoa(remainder)

		gtins = append(gtins, upc+remainderString)
	}

	if _, err := os.Stat(directory + "/answer.txt"); err == nil {
		e := os.Remove(directory + "/answer.txt")
		Error(e)
	}

	answerFile, err := os.Create(directory + "/answer.txt")
	Error(err)

	defer answerFile.Close()

	for _, gtin := range gtins {
		_, err := answerFile.WriteString(gtin + "\n")
		Error(err)
	}
}
