# -*- coding: utf-8 -*-
#!/usr/bin/env python

# These two lines are only needed if you don't put the script directly into
# the installation directory
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
sys.path.append('/usr/share/inkscape/extensions')

import inkex, simplestyle, tempfile, os, re, subprocess

class ExportJPEG(inkex.Effect):
    def __init__(self):
        inkex.Effect.__init__(self)
        self.OptionParser.add_option("-r", "--resolution", action="store", type="int", dest="resolution", default="300", help="Resolution for rasterization (dpi)")
        self.OptionParser.add_option("-k", "--export_area", action="store", type="string", dest="export_area", default="", help="Limit export to the object with ID")
        self.OptionParser.add_option("-g", "--set_icc", action="store", type="inkbool", dest="set_icc", default=True, help="ICC Profile")

    def output(self):
        out = open(tempfile.gettempdir() + os.sep + file_name + '.jpg','rb')
        if os.name == 'nt':
            try:
                import msvcrt
                msvcrt.setmode(1, os.O_BINARY)
            except:
                pass
        sys.stdout.write(out.read())
        out.close()

    def effect(self):

        svg = open(self.svg_file, 'r').read()

        resolution = str(int(self.options.resolution))

        file_name = "image"

        do_win_inkscape = ""
        null_dir = " > /dev/null"

        if os.sep == "\\":
            do_win_inkscape = "c"
            null_dir = ""
            inkscape_config = open(os.getenv("APPDATA") + '\inkscape\preferences.xml', 'r').read()
        else:
            inkscape_config = open(os.getenv("HOME") + '/.config/inkscape/preferences.xml', 'r').read()


        #inkscape_config = open(os.getenv("HOME") + '/.config/inkscape/preferences.xml', 'r').read()
        rgb_profile = '"' + inkscape_config.split('id="displayprofile"')[1].split('uri="')[1].split('" />')[0] + '"'
        cmyk_profile = '"' + inkscape_config.split('id="softproof"')[1].split('uri="')[1].split('" />')[0] + '"'

        export_area = []
        if self.options.export_area != "":
            for i in range(len(self.options.export_area.split(","))):
                export_area.append("--export-id=" + self.options.export_area.split(",")[i])
        else:
            export_area.append("--export-area-page")

        export_area_only = ''

        #for i in range(len(svg.split('\n'))):
            #if 'sodipodi:docname="' in str(svg).split('\n')[i]:
                #file_name = str(svg).split('sodipodi:docname="')[1].split('"')[0][:-4]

        #for i in range(len(export_area)):
            #string_inkscape_exec = ''
            ##subprocess.Popen(['inkscape', '-z', '--file=' + self.svg_file, export_area[i],'--export-dpi=' + resolution , '--export-background-opacity=1', '--export-png=' + tempfile.gettempdir() + os.sep + file_name + ".png"], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'), stdin=subprocess.PIPE).wait()
            #string_inkscape_exec = ' --file=' + self.svg_file + ' ' + export_area[i] + ' ' + '--export-dpi=' + resolution + ' ' + '--export-background-opacity=1 --export-png=' + tempfile.gettempdir() + os.sep + file_name + ".png"
            #inkscape_exec = subprocess.Popen(['inkscape -z --shell'], shell=True, stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'), stdin=subprocess.PIPE).wait()# + ['>', os.devnull])
        #inkscape_exec.communicate(input=string_inkscape_exec)

        #if self.options.set_icc:
            ##subprocess.Popen(['convert', tempfile.gettempdir() + os.sep + file_name + ".png", '-profile', rgb_profile, tempfile.gettempdir() + os.sep + file_name + ".png"]).wait()
            #subprocess.Popen(['convert', tempfile.gettempdir() + os.sep + file_name + ".png", '-colorspace', 'CMYK', tempfile.gettempdir() + os.sep + file_name + ".tif"]).wait()
            #subprocess.Popen(['convert', tempfile.gettempdir() + os.sep + file_name + ".tif", '-profile', cmyk_profile, '-profile', rgb_profile, tempfile.gettempdir() + os.sep + file_name + ".jpg"]).wait()
        #else:
            #subprocess.Popen(['convert', tempfile.gettempdir() + os.sep + file_name + ".png", tempfile.gettempdir() + os.sep + file_name + ".jpg"]).wait()

        for i in range(len(export_area)):
            os.system('inkscape' + ' -z --file="' + self.svg_file + '" ' + export_area[i] + ' --export-dpi=' + resolution + ' --export-background-opacity=1 --export-png="' + tempfile.gettempdir() + os.sep + file_name + '.png"' + null_dir)
            #subprocess.Popen(['inkscape', '-z', '--file=' + self.svg_file, export_area[i],'--export-dpi=' + resolution , '--export-background-opacity=1', '--export-png=' + tempfile.gettempdir() + os.sep + file_name + ".png"], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'), stdin=subprocess.PIPE).wait()
            if self.options.set_icc:

                #os.system('convert "' + tempfile.gettempdir() + os.sep + file_name + '.png"' + ' -profile "' + rgb_profile + '" "' + tempfile.gettempdir() + os.sep + file_name + '.png"')
                os.system('convert ' + tempfile.gettempdir() + os.sep + file_name + '.png' + ' -profile ' + rgb_profile + ' -profile ' + cmyk_profile + ' ' + tempfile.gettempdir() + os.sep + file_name + '.tif')
                #os.system('convert ' + tempfile.gettempdir() + os.sep + file_name + ".tif" + ' -profile ' + cmyk_profile + ' -profile ' + rgb_profile + " " + tempfile.gettempdir() + os.sep + file_name + ".png")
                os.system('convert ' + tempfile.gettempdir() + os.sep + file_name + '.tif' + ' -profile ' + rgb_profile + ' ' + tempfile.gettempdir() + os.sep + file_name + '.jpg')
                #os.system('convert ' + tempfile.gettempdir() + os.sep + file_name + '.tif ' + tempfile.gettempdir() + os.sep + file_name + '.png')

        #os.system('convert "' + tempfile.gettempdir() + os.sep + file_name + '.png' + '" "' + tempfile.gettempdir() + os.sep + file_name + '.jpg"')


effect = ExportJPEG()
effect.affect()
