import sys
import csv
from statis2 import Statis2
from optparse import OptionParser

class Cli:
    def __init__(self, args):
        self.args = args

    @staticmethod
    def start():
        Cli(sys.argv).run()

    def run(self):
        parser = OptionParser()
        parser.add_option('-v', '--version', dest='version',
            action = 'store_true', help = 'show version'
        )
        parser.add_option('-i', '--input', dest = 'input',
            help = '[REQUIRED] path to csv file with input data', metavar = 'FILE'
        )
        parser.add_option('-o', '--output', dest = 'output', default = 'normalized.csv',
            help = 'path to result file. Default is ./normalized.csv', metavar = 'FILE'
        )
        (options, args) = parser.parse_args()

        if options.version:
            self.print_version_action()

        if not options.input:
            parser.print_help()
            exit(0)

        self.normalize_action(options.input, options.output)

    def print_version_action(self):
        print Statis2.VERSION
        exit(0)

    def normalize_action(self, input, output):
        result = Statis2(self.__read_input(input)).run()
        self.__write_output(output, result)

    def __read_input(self, input):
        data = []
        with open(input, 'rb') as csvfile:
          reader = csv.reader(csvfile, delimiter=',', quotechar='"')
          for row in reader:
              data.append(row)

        for row in data[1:]:
            for j in range(len(row)):
                val = row[j]
                row[j] = self.__float_value(val)

        return data

    def __float_value(self, value):
        try:
            return float(value)
        except ValueError:
            return 0

    def __write_output(self, output, data):
        with open(output, 'wb') as csvfile:
            writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            writer.writerows(data)

if __name__ == "__main__":
    Cli(sys.argv).run()
