import os
import sys
import re
import cgi
import requests


from tklib.tkapplication import tkApplication



class tkApplication_CGI(tkApplication):
    def __init__(self, **args):
        super().__init__(**args)

        self.initialized = False
        self.closed      = False
        self.form = cgi.FieldStorage() 

        self.update(**args)

    def __del__(self):
        super(tkApplication, self).__del__()

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

    def init_html(self, charset = 'utf-8', lang = 'ja', extra_headers = None, header_only = False):
        if self.initialized:
            return

        self.initialized = True

        print("Content-Type: text/html")
        print("")
        print("<!DOCTYPE html>")
        print("<html>")
        print("<head>")
        print(f'<meta http-equiv="Content-Language" content="{lang}">')
        print(f'<meta http-equiv="Content-Type" content="text/html; charset={charset}" />')
        if extra_headers:
            print(extra_headers)
        print("</head>")
        
        if not header_only:
            print("")
            print("<body>")

    def end_html(self):
        if self.closed:
            return

        self.closed = True
        print("</body>")
        print("</html>")

    def get_cgi_mode(self):
        if(os.environ['REQUEST_METHOD'] == "GET"):
            return 'get'
        if(os.environ['REQUEST_METHOD'] == "POST"):
            return 'post'
        return ''
    
    def get_args(self):
        line = os.environ.get('QUERY_STRING')
        strs = line.split('&')
        inf = {}
        for s in strs:
            a = s.split('=')
            inf[a[0]] = a[1]
        return inf

    def is_get(self):
        if(os.environ['REQUEST_METHOD'] == "GET"):
            return True
        return False

    def is_post(self):
        if(os.environ['REQUEST_METHOD'] == "POST"):
            return True
        return False

    def getvalue(self, key, defval = None):
        return self.form.getvalue(key, defval)

    def getfirst(self, key, defval = None):
        return self.form.getfirst(key, defval)

    def validate_path(self, path, keys = 'all'):
        if path is None or len(path) == 0:
            return ''

        if ('all' in keys or 'top_dir' in keys) and (path[0] == '/' or path[0] == '\\' or ':\\' in path or ':/' in path or '//' in path):
            return f'Illeagal access to top directory [{path}]'

        if ('all' in keys or 'upper_dir' in keys) and '..' in path:
            return f'Illeagal access to upper directory [{path}]'

        if ('all' in keys or 'invalid_char') in keys and re.search(r'[\<\>\|]', path):
            return f'Illeagal characters in [{path}]'

        return ''
        