# coding: utf-8

from ru.curs.showcase.core.jython import JythonProc
from ru.curs.showcase.core.jython import JythonDTO
from ru.curs.showcase.runtime import ConnectionFactory
from xml.dom.minidom import *
from java.util import Properties
from java.sql import *
import urllib

# init vars
main = ""
add = ""
session = ""
filterContext = ""
elementId = ""


class get_pin_mz(JythonProc):
    def execute(self, context):
        global main, add, session, filterContext, elementId
        main = context.getMain()
        if context.getAdditional():
            add = context.getAdditional()
        session = context.getSession()
        if context.getFilter():
            filterContext = context.getFilter()
        return mainproc()


def mainproc():
    #raise Exception(sid)

    sessioncntx = parseString(unicode(session))
    sidelem = sessioncntx.getElementsByTagName('sid')[0]
    sid = sidelem.firstChild.nodeValue

    jdbc_url_psql_rgmu = "jdbc:sqlserver://172.16.1.155\\FUV"
    jdbc_url_psql_local = "jdbc:sqlserver://172.16.1.155\\FUV"
    propspsql = Properties()
    propspsql.put('user', "sa")
    propspsql.put('password', "F708420Dx")

    import com.microsoft.sqlserver.jdbc.SQLServerDriver as DriverMSSQL
    try:
        db1 = DriverMSSQL().connect(jdbc_url_psql_local, propspsql)
    except:
        db1 = DriverMSSQL().connect(jdbc_url_psql_rgmu, propspsql)

    pin = getPinMZ()
    if pin is not None:
        updateuser = db1.prepareStatement("update dbVector.authserver.users_auth_server SET pinmz = ? where sid = ?")
        updateuser.setString(1, pin)
        updateuser.setString(2, sid)
        updateuser.execute()


def getPinMZ():
    u'''Отправляем запрос на сайт МЗ и получаем в ответ xml с PIN.'''

    linkparams = {'pin_customer': '2medMos',
                 'pin_series': 'NMO-01-2014',
                 'pin_type': 'full',
                 'pin_duration': '365',
                 'pin_max_date_on': '01-01-2014',
                 'pin_max_date_off': '31-12-2015'}

    link = u'''http://www.sovetnmo.ru/cgi-bin/unishell/?usr_data=gdaccessdata(edu_results_log,get_pccode(%(pin_customer)s,%(pin_series)s,%(pin_type)s,%(pin_duration)s,%(pin_max_date_on)s,%(pin_max_date_off)s))''' % linkparams

    uo = urllib.urlopen(link)
    resp = uo.read()

    resp_parsed = parseString(resp)
    try:
        pinelem = resp_parsed.getElementsByTagName('code')[0]
        pin = pinelem.firstChild.nodeValue

        return pin
    except:
        return None



if __name__ == "__main__":
    mainproc()
