#-*- coding: utf-8 -*-

# Copyright 2012-2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

from __future__ import absolute_import
from .Box import MainWgt
from calculate.consolegui import qt
#from mainmenu import MainMenu

import os
# import ConfigParser
import calculate.lib.configparser as ConfigParser
import gettext
_ = gettext.gettext
class ApiClient(qt.QWidget):
    def __init__(self, app, tabs):
        super().__init__()
        self.app = app
        self._parent = tabs

        self.VarsGui = tabs.VarsGui
        try:
            self.Version = self.VarsGui.Get('cl_ver')
        except:
            self.Version = ''

        self.Name = 'Calculate Console'

        # Initialization of system variables
        self.VarsApi = self.VarsGui

        # Initialization other variables
        self.homePath = self.VarsGui.Get('ur_home_path')
        path_to_cert = self.VarsGui.Get('core.cl_client_cert_dir')
        self.path_to_cert = path_to_cert.replace("~",self.homePath)

        # other variable 
        self.default_host = 'localhost'
        self.default_port = self.VarsGui.Get('core.cl_core_port')

        self.client = None
        self.host_name = None

        self.res_layout = qt.QVBoxLayout(self)

        self.process_dict = {}
        self.param_objects = {}
        self.method_names = {}

        # read from users configuratuon file
        user_config = self.VarsGui.Get('cl_gui_config_path')
        self.user_config = user_config.replace("~",self.homePath)
        if not os.path.isfile(self.user_config):
            self.create_user_config()
        self.read_user_config(self.user_config)

        # create default certificates directories
        if not os.path.exists (self.path_to_cert):
            os.mkdir(self.path_to_cert)

        self.MainWidget = MainWgt(self)    
        # Translate top menu
        self.MainWidget.topmenu.refresh()

    def create_user_config(self):
        if not os.path.exists ('~/.calculate'.replace("~",self.homePath)):
            os.mkdir('~/.calculate'.replace("~",self.homePath))
        if not os.path.exists ('~/.calculate/console_gui'.replace \
                                                        ("~",self.homePath)):
            os.mkdir('~/.calculate/console_gui'.replace("~",self.homePath))
        if not os.path.isfile (self.user_config):
            cfg_text = '[other]\n\n'\
                       '[gui]\n'
            fp = open(self.user_config, 'w')
            fp.write(cfg_text)
            fp.close()

    def read_user_config(self, config):
        config = ConfigParser.ConfigParser()
        config.read(self.user_config)

        ###################### other ##########################
        import gettext
        import locale
        # get language
        try:
            self.lang = config.get('other', 'lang')
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            # default_locale = gettext.locale.getdefaultlocale()
            default_locale = locale.getdefaultlocale()
            if default_locale[0]:
                self.lang = default_locale[0][:2]
            else:
                self.lang = "en"
        if hasattr (self._parent, 'lang'):
            if self._parent.lang:
                self.lang = self._parent.lang

        try:
            lang = gettext.translation('cl_consolegui3', languages=[self.lang])
        except (TypeError,IOError):
            self.lang = 'en'
            lang = gettext.translation('cl_consolegui3',languages=[],fallback=True)

        try:
            lang.install()
            # lang.install(unicode=True)
        except UnboundLocalError:
            pass
        try:
            # Translate top menu
            self.MainWidget.topmenu.refresh()
        except AttributeError:
            pass

        self._parent.translate(self.lang)

        # get path to certificates
        try:
            path_to_cert = config.get('other', 'path_to_cert')
            self.path_to_cert = path_to_cert.replace("~",self.homePath)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            pass
        if self.path_to_cert.lower() == 'no':
            path_to_cert = self.VarsGui.Get('core.cl_client_cert_dir')
            self.path_to_cert = path_to_cert.replace("~",self.homePath)

        try:
            timeout = config.get('other', 'timeout')
            self.timeout = int(timeout)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \
                ValueError):
            self.timeout = 5

        ###################### gui ##########################
        try:
            height_image = config.get('gui', 'height_image')
            self.height_image = int(height_image)
            if self.height_image < 0 or self.height_image > 512:
                self.height_image = 192
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \
                ValueError):
            self.height_image = 192

        try:
            expert = config.get('gui', 'expert')
            self.expert = int(expert)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \
                ValueError):
            self.expert = 1

        try:
            count_row = config.get('gui', 'count_row')
            self.count_row_res_table = int(count_row)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError, \
                ValueError):
            self.count_row_res_table = 20
