import sys
import re

TYPE_BATTLEFIELD = "Battlefield"


def print_usage():
    print(""" 
    Star Wars: Destiny trade list builder

    Usage:
    $>python destiny.py <target-file>

    where <target-file> is the text-file to process.

    This file should be generated by logging into swdestiny.com, going to 'My collection',
    selecting all (Ctrl/Cmd + A), pasting into an empty file, and saving.
    """)

# Opens file, and returns it as a list of lines
def open_file(path):
    f = open(path, 'r+')
    lines = f.readlines()
    f.close()
    return lines

def write_file(path, haves, wants):
    output = open(path, 'w')

    output.write("HAVES")
    for card in haves:
        qty = 0
        if card.type == TYPE_BATTLEFIELD:
            qty = card.qty - 1
        else:
            qty = card.qty - 2
        output.write("\n%dx %s\t\t(%s)" % (qty, card.name, card.set_string))

    output.write("\n\nWANTS")
    for card in wants:
        qty = 0
        if card.type == TYPE_BATTLEFIELD:
            qty = 1 #you always only want 1 battlefield
        else:
            qty = 2 - card.qty
        output.write("\n%dx %s\t\t(%s)" % (qty, card.name, card.set_string))

    output.close()

def strip_header(lines):
    return lines[19:]

def strip_footer(lines):
    return lines[:-11]

class Card:
    def __init__(self, line):
        split = line.split("\t")
        self.name = split[0].lstrip().rstrip()
        self.qty = self.parse_qty(split[1])
        self.type = split[6]
        self.rarity = split[7]
        self.set = self.parse_set(split[-1].lstrip().rstrip())
        self.number = self.parse_number(split[-1])
        self.set_string = split[-1].lstrip().rstrip()
    
    # Pulls number from quantity string
    def parse_qty(self, qty_string):
        found = re.findall(r'\d+', qty_string)
        return int(found[0])
    
    # Parse the card's set name.
    # Assumes the last word is set number
    def parse_set(self, set_string):
        return set_string.rsplit(" ", 1)[0]

    # Parse the card's number in the set. 
    # Assumes the last word is set number
    def parse_number(self, number_string):
        return int(number_string.rsplit(" ", 1)[1])
    
def check_usage():
    num_args = len(sys.argv)

    if num_args < 2:
        print_usage()
        sys.exit()

def extract_filename_and_extension(filename):
    split_name = filename.rsplit(".", 1)
    return (split_name[0], split_name[1])

# run script
check_usage()

input_file = sys.argv[1]
file_lines = open_file(input_file)
file_lines = strip_header(file_lines)
file_lines = strip_footer(file_lines)

cards = []
for line in file_lines:
    cards.append(Card(line))

haves = []
wants = []

for card in cards:
    if card.type == TYPE_BATTLEFIELD:
        if card.qty < 1:
            wants.append(card)
        elif card.qty > 1:
            haves.append(card)
    else:
        if card.qty < 2:
            wants.append(card)
        elif card.qty > 2:
            haves.append(card)

(filename, extension) = extract_filename_and_extension(input_file)
write_file(filename+"_trades."+extension, haves, wants)
