from ideatree.models import Colors 
from django.http import HttpResponse
import sys
#import pdb


def importColors():
  try:
    # NOTE: Tables online are incomplete, so I've combined several, using a unique index on the db to weed out duplicates.
    with open('/var/www/ideatree/ideatree/utils/x11MasterTableWithDuplicates.csv') as fileIn:
    #with open('ideatree/utils/x11TableNum3.csv') as fileIn:
    #with open('ideatree/utils/x11ColorTable.csv') as fileIn:
    #with open('ideatree/utils/x11WithGreySpelling.csv') as fileIn:  
      i = 0
      for line in fileIn:  
        i += 1
        line =  line.split(',')
        colorname=line[0].lower().strip()
        hexvalue=line[1].lower().strip()
        #print(str(colorname) +","+ str(hexvalue))
        if colorname and hexvalue:
          created = Colors.objects.update_or_create(colorname=colorname, defaults={'colorname': colorname, 'hexvalue':hexvalue},)
          # If a line exists with this colorname then update with the same colorname. 
          # Else create new record with this colorname and hexvalue.
      return HttpResponse("Total records updated or created:"+ str(i))
  except Exception as err:
      print("Import Colors table error:"+ str(err), file=sys.stderr)
      return HttpResponse(str(err))
      


