"""
------------------------------------------------------------------------------
--                                                                          --
--                                 LAB 07                                   --
--                                                                          --
--                             L A B 0 7 . P Y                              --
--                                                                          --
------------------------------------------------------------------------------
-- <Your Name Here>                                                         --
--                                                                          --
-- <Class Name Here>                                                        --
--                                                                          --
------------------------------------------------------------------------------
-- This file contains a Final Fantasy VII save game class along with some   --
-- functions for reading saves from and writing them to files.  The saves   --
-- are written out in CSV format rather than the original binary format of  --
-- the actual save game files.                                              --
--                                                                          --
------------------------------------------------------------------------------
"""

import ff7

def read_saves(fname):
    """
    Opens fname for binary reading and reads all of its saves into a list of
    FF7Save objects.
    """
    in_file = open(fname, 'rb')
    saves = []

    for i in range(15):
        try:
            save_str = ff7.read_save_string(in_file)
            saves += [create_ff7save(save_str)]
        except IOError:
            break

    in_file.close()
    return saves

def write_saves_to_csv(saves, fname):
    """
    Takes a list saves of FF7Save objects and a file fname. Writes the elements
    of saves in CSV format to fname.
    """
    out_file = open(fname, 'w')
    out_file.write('Name,Level,Current HP,Max HP,Current MP,Max MP,Character 1,Character 2,Character 3,Gil,Location\n')

    for save in saves:
        out_file.write(to_csv_string(save) + '\n')

    out_file.close()

def create_ff7save(save_string):
    """
    Takes a string of information s as returned by ff7.read_save_string and
    constructs an FF7Save object from it
    """
    self = {}

    for elt in save_string.split(';'):
        if 'Level' in elt:
            self['level'] = int(elt.split(' : ')[1])
        elif 'HP' in elt:
            both_hp = elt.split(' : ')[1]
            both_hp = both_hp.split('/')
            self['current_hp'] = int(both_hp[0])
            self['max_hp'] = int(both_hp[1])

        #########

    return self

def to_csv_string(self):
    csv = self['name'] + ','
    csv += str(self['level']) + ',' 
    ###
    ###
    return csv
