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

# Copyright 2012-2013 Calculate Ltd. 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 Box import MainWgt
from PySide import QtGui
#from mainmenu import MainMenu

import os
import ConfigParser

class ApiClient(QtGui.QWidget):
    def __init__(self, app, tabs):
        super(ApiClient, self).__init__()
        self.app = app
        self._parent = tabs

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

        try:
            self.Name = self.VarsGui.Get('cl_name')
        except:
            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 = '8888'

        self.client = None
        self.host_name = None

        self.res_layout = QtGui.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
        # get language
        try:
            self.lang = config.get('other', 'lang')
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            self.lang = ''
        if hasattr (self._parent, 'lang'):
            if self._parent.lang:
                self.lang = self._parent.lang

        try:
            lang = gettext.translation('cl_consolegui3', languages=[self.lang])
        except IOError:
            try:
                self.lang = gettext.locale.getdefaultlocale()[0][:2]
                lang = gettext.translation('cl_consolegui3', \
                                           languages=[self.lang])
            except (TypeError,IOError) as e:
                self.lang = 'en'
                lang = gettext.translation('cl_consolegui3',fallback=True)

        try:
            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
