import io
from . import GCUT as GCUT
from . import GCStrings as GCStrings
from . import GCDisplaySettings as GCDisplaySettings

SBTF_TEXT = 1
SBTF_RTF = 2
SBTF_HTML = 3
SBTF_XML = 4

class GCStringBuilder:
    def __init__(self,targetStream):
        self.fontSizeH1 = 28
        self.fontSizeH2 = 24
        self.fontSizeText = 20
        self.fontSizeNote = 18
        self.Format = SBTF_TEXT
        self.Target = targetStream

    def AppendString(self,text):
        self.Target.write(text)

    def AppendBoldString(self,text):
        if self.Format == SBTF_TEXT:
            self.Target.write(text)
        elif self.Format == SBTF_RTF:
            self.Target.write("{\\b ")
            self.Target.write(text)
            self.Target.write("}")
        elif self.Format == SBTF_HTML:
            self.Target.write("<b>")
            self.Target.write(text)
            self.Target.write("</b>")

    def AppendLine(self, text=''):
        if self.Format == SBTF_TEXT:
            self.Target.write(text)
            self.Target.write("\r\n")
        elif self.Format == SBTF_RTF:
            self.Target.write("\r\n\\par ")
            self.Target.write(text)
        elif self.Format == SBTF_HTML:
            self.Target.write("<br>")
            self.Target.write(text)

    def initWithString(self, str):
        self.Target.write(str)

    def AppendHeader1(self, text):
        if self.Format == SBTF_TEXT:
            lt = int((80 - len(text))/2)
            self.Target.write(''.rjust(lt,'=') + text + ''.rjust(lt,'='))
            self.Target.write('\r\n')
        elif self.Format == SBTF_RTF:
            self.Target.write("\\par\\pard{{\\f2\\fs{} {} }}".format(self.fontSizeH1,text))

    def AppendHeader3(self, text, fillChar='='):
        lt = int((80 - len(text))/2)
        t = ''.rjust(lt,fillChar) + text + ''.rjust(lt,fillChar)
        if self.Format == SBTF_TEXT:
            self.Target.write(t)
            self.Target.write('\r\n')
        elif self.Format == SBTF_RTF:
            self.Target.write("\\par\\pard{{\\f2\\fs{} {} }}".format(self.fontSizeH1,t))
        elif self.Format == SBTF_HTML:
            self.Target.write("<span style='color:#110033'>")
            self.Target.write(text)
            self.Target.write('</span>')


    def AppendHeader2(self, text):
        if self.Format == SBTF_TEXT:
            lt = int((80 - len(text))/2)
            self.Target.write(''.rjust(lt,'-') + text + ''.rjust(lt,'-'))
            self.Target.write('\r\n')
        elif self.Format == SBTF_RTF:
            self.Target.write("\\par\\pard{{\\f2\\fs{} {} }}".format(self.fontSizeH2,text))

    def AppendDocumentHeader(self):
        if self.Format == SBTF_TEXT:
            pass
        elif self.Format == SBTF_RTF:
            color_table = ''
            file_name = os.path.join(os.path.dirname(__file__), 'res', 'rtf_color_table.txt')
            with open(file_name) as rfile:
                color_table = rfile.read()
            self.Target.write("{\\rtf1\\ansi\\ansicpg1252\\deff2\\deflang1033{\\fonttbl{\\f0\\fswiss\\fcharset0 Lucida Console;} {\\f1\\fswiss\\fcharset0 Arial;}{\\f2\\froman\\fprq2\\fcharset0 Book Antiqua;}} {\\colortbl ;")
            self.Target.write(color_table)
            self.Target.write("}{\\*\\generator GCAL;}\\viewkind4\\uc1\\pard\\f0\\fs20 ")
            self.Target.write("\\par\\pard\\f2\\fs")
            self.Target.write(str(self.fontSizeText))
            self.Target.write("\r\n")

    def AppendDocumentTail(self):
        if self.Format == SBTF_TEXT:
            pass
        elif self.Format == SBTF_RTF:
            self.Target.write("}")
        elif self.Format == SBTF_HTML:
            self.Target.write("</body>")
            self.Target.write("</html>")

    def AppendNote(self):
        self.AppendLine()
        self.AppendLine()
        self.AppendSeparatorWithWidth(80)
        self.AppendLine()
        self.AppendBoldString("Notes:")
        self.AppendLine()
        self.AppendLine()
        self.AppendLine("DST - Time is in \'Daylight Saving Time\'")
        self.AppendLine("LT  - Time is in \'Local Time\'\r\n")

        if GCDisplaySettings.getValue(9) > 0 or GCDisplaySettings.getValue(10) > 0 or GCDisplaySettings.getValue(11) > 0 or GCDisplaySettings.getValue(12) > 0:
            self.AppendLine("(*) - value at the moment of sunrise")

        # last line
        self.AppendLine()
        self.AppendString("Generated by ")
        self.AppendString(GCStrings.getString(132))

    def AppendSeparatorWithWidth(self,width):
        self.AppendString('-' * width);

    def AppendTwoColumnText(self,pText,pText2):
        if self.Format == SBTF_TEXT:
            str = '{}{}'.format(pText.ljust(17,' '), pText2).rstrip() + "\r\n"
        elif self.Format == SBTF_RTF:
            str = '\\par {}\\tab {}'.format(pText, pText2)
        self.Target.write(str)

def unittests():
    GCUT.info('string builder')
    s = io.StringIO()
    sb = GCStringBuilder(s)
    GCUT.msg('testing TEXT')
    sb.AppendString('aaa')
    sb.AppendDocumentHeader()
    sb.AppendDocumentTail()
    sb.AppendNote()
    sb.AppendSeparatorWithWidth(30)
    GCUT.msg('testing RTF')
    sb.AppendString('aaa')
    sb.AppendBoldString('aaa')
    sb.AppendDocumentHeader()
    sb.AppendDocumentTail()
    sb.AppendNote()
    sb.AppendSeparatorWithWidth(30)
