import csv


from tklib.tkutils import terminate, pfloat, pint
from tklib.tksci.tkmatrix import make_matrix1
from tklib.tkdatafile import tkDataFile


def savecsv(outfile, x, y, ys):
    try: 
        print("Write to [{}]".format(outfile))
        f = open(outfile, 'w')
    except:
#    except IOError:
        print("Error: Can not write to [{}]".format(outfile))
    else:
        fout = csv.writer(f, lineterminator='\n')
        fout.writerow(('x', 'y(raw)', 'y(smooth)'))
#        fout.writerows(data)
        for i in range(0, len(x)):
            fout.writerow((x[i], y[i], ys[i]))
        f.close()


class tkCSV(tkDataFile):
    def __init__(self, path = None, mode = 'r', OpenFile = 1, data_only = True, **args):
#        super(tkFile, self).__init__(path, mode, **args)
        self.fp    = None
        self.path  = None
        self.mode  = None
        self.path  = self.IfYes(path is not None, path, self.path)
        self.mode  = self.IfYes(mode is not None, mode, self.mode)
        self.cur_row = 0
        self.cur_col = 0
        self.wb  = None
        self.ws  = None
        self.update(**args)
        
        if OpenFile and self.path is not None:
            self.Open(self.path, self.mode, data_only)

    def __del__(self):
        self.Close()

    def __str__(self):
        return self.ClassPath()


    def Read_minimum_matrix(self, close_fp = False, delimiter = ',', force_numeric = True):
        self.Open(self.path, 'r')
        f = csv.reader(self.fp, delimiter = delimiter)

        labels = []
        row    = next(f)
        for i in range(len(row)):
            v = row[i]
            if v is None or v == '':
                break
            labels.append(v)

        ncol   = len(labels)
#        print("header=", labels)

        datalist = make_matrix1(ncol, type = 'list')
        for row in f:
#            print("row=", row)
            if row is None or len(row) < ncol:
                break

            for icol in range(ncol):
                if force_numeric:
                    val = pfloat(row[icol])
                else:
                    val = pfloat(row[icol], defval = row[icol])
                datalist[icol].append(val)

            icol += 1

        if close_fp:
            self.Close()

        self.labelarray    = labels
        self.datalistarray = datalist
#        print("data=", self.datalistarray)

#        print("labels=", labels)
#        print("data=", datalist)
        
        return labels, datalist
 