# coding: utf-8

from ru.curs.showcase.core.jython import JythonProc
from ru.curs.showcase.core.jython import JythonDTO
from ru.curs.showcase.app.api import UserMessage
from ru.curs.showcase.runtime import ConnectionFactory
from xml.dom.minidom import *
from java.util import Properties, UUID
from java.sql import *


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


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


def mainproc():
    #raise Exception(sid)
    roles = ['external']
    pyConn = ConnectionFactory.getPyConnection()
    try:
        sessioncntx = parseString(unicode(session))
        sidelem = sessioncntx.getElementsByTagName('sid')[0]
        sid = sidelem.firstChild.nodeValue

        cur = pyConn.cursor()
        cur.execute("select personUid from dbo.usersAuthServerFUV where uid=?", [(sid)])
        personid = cur.fetchone()[0]
        if personid is not None:
            cur.execute("select distinct roleid from fuved.person_cycleAsEvent_eok where personid=?", [(personid)])
            for rec in cur.fetchall():
                roles.append(rec[0])
            cur.execute("select distinct roleid from fuved.administration where personid=?", [(personid)])
            for rec in cur.fetchall():
                roles.append(rec[0])
    except:
        pass
    finally:
        pyConn.close()

    #lcab = u'''<p><a href="?userdata=listenercab" target="_self"><b>Обучение на циклах факультета усовершенствования врачей</b></a></p>'''
    lcab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=listenercab';window.open(url,'_self');">
                            <span class="xforms-label">Обучение на циклах</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
    [lcab, lprops] = learningButton(sid)

    if 'tutor' in roles and not 'superviser' in roles:
        #tutcab = u'''<p><a href="?userdata=tutorcab" target="_self"><b>Личный кабинет тьютора</b></a></p>'''
        tutcab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=tutorcab';window.open(url,'_self');">
                            <span class="xforms-label">Личный кабинет тьютора</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
    elif 'superviser' in roles:
        tutcab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=tutorcab';window.open(url,'_self');">
                            <span class="xforms-label">Личный кабинет супервайзера</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''

    else:
        tutcab = u''''''

    if 'contentmanager' in roles or 'contentauthor' in roles or 'reviewer' in roles:
        #cmcab = u'''<p><a href="?userdata=author" target="_self"><b>Личный кабинет контентменеджера</b></a></p>'''
        cmcab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=author';window.open(url,'_self');">
                            <span class="xforms-label">Управление контентом</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
    else:
        cmcab = u''''''

    if 'deanstaff' in roles:
        #dscab = u'''<p><a href="?userdata=deancab" target="_self"><b>Личный кабинет сотрудника деканата</b></a></p>'''
        dscab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=deancab';window.open(url,'_self');">
                            <span class="xforms-label">Организация обучения</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
    else:
        dscab = u''''''



    defaultlink = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=edean';window.open(url,'_self');">
                            <span class="xforms-label">Электронный деканат ФДПО</span>
                            </button>
                        </span>            
                    </span>
                </div></p>
				'''

    welcometext = u'''<h2>Уважаемые слушатели!</h2>
                    <p><b>Перед началом работы в системе электронного обучения с применением дистанционных технологий 
                    на факультете дополнительного профессионального образования Российского национального исследовательского медицинского
                     университета имени Н. И. Пирогова (ФДПО), пожалуйста, ознакомьтесь с соответствующей инструкцией.</b></p>
                    <p><a href="http://rsmu.ru/12179.html" target="_blank">Инструкция для слушателей ФДПО</a></p>
					<p><a href="http://rsmu.ru/13915.html" target="_blank">Инструкция по работе с электронным деканатом ФДПО</a></p>'''
    if userOnMZCycles(sid):
        mzlink = checkPinMZ(sid)
    else:
        mzlink = ['', '<properties></properties>']
    bttable = u'''<div><table><tr><td>''' + defaultlink + lcab + dscab + tutcab + cmcab + mzlink[0] + '''</td><td width="50px"></td><td>''' + welcometext + '''</td></tr></table></div>'''
    #settings = None
    #res = JythonDTO(u'''<div>''' + defaultlink + lcab + tutcab + cmcab + dscab + u'''</div>''', settings)
    properties = ''''''
    if mzlink[1] is not None:
        properties += mzlink[1]
    if lprops is not None:
        properties += lprops
    properties = properties.replace('</properties><properties>', '')
    res = JythonDTO(bttable, properties)
    return res

def checkPinMZ(sid):
    u'''Проверяем, имеет ли данный sid pin для доступа к Минздраву.'''

    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)
    c1 = db1.createStatement()
    usersselect = c1.executeQuery("select u.uid, u.login, u.pinmz, r.name, r.surname, r.patronymic from dbVector.authserver.users_auth_server u inner join dbVector.journals.reg_data r on u.sid=r.sid where u.sid='" + sid + "'")
    haspinmz = False

    while usersselect.next():
        useruid = usersselect.getString('uid')
        #login = usersselect.getString('login')
        pinmz = usersselect.getString('pinmz')
        surname = usersselect.getString('surname') if usersselect.getString('surname') is not None else ''
        name = usersselect.getString('name') if usersselect.getString('name') is not None else ''
        patronymic = usersselect.getString('patronymic') if usersselect.getString('patronymic') is not None else ''
        #raise Exception(name, surname, patronymic)
        if pinmz is not None:
            haspinmz = True
            link = u"'http://www.sovetnmo.ru/cgi-bin/unishell/?usr_data=navigate(index)&amp;seamless-access=%s&amp;user_id=%s&amp;salutation=%s&amp;familyname=%s&amp;nameandfname=%s&amp;pin=%s'" % ('2-med.ru', useruid, u'Уважаемый коллега.', surname,
                                                                      u'%s %s' % (name, patronymic), pinmz)

            btn = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url=''' + link + ''';window.open(url,'_blank');">
                            <span class="xforms-label">Перейти на сайт НМО МЗ</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
            break

    if haspinmz:
        return [btn, None]
    else:
        btn = u'''<div class="newbutton">
                <span class="blue xforms-trigger">
                    <span class="value">
                        <button style="width: 270px; text-align: center" onclick="gwtWebTextFunc('%s','getPinMZ');">
                            <span class="xforms-label">Получить доступ к сайту НМО МЗ</span>
                        </button>
                    </span>            
                </span>
            </div> ''' % elementId
        properties = u'''<properties>
            <event name="single_click" linkId="getPinMZ">
                 <action >
                    <main_context>current</main_context>
                    <server>
                        <activity id="getPinMZ" name="get_pin_mz.py">
                             <add_context></add_context>  
                        </activity>             
                    </server>
                    <datapanel type="current" tab="current">
                        <element id="link_webtext">
                            <add_context></add_context>
                        </element>
                    </datapanel>
                </action>
            </event>
        </properties>'''

        return [btn, properties]

    c1.close()
    db1.close()

def userOnMZCycles(sid):
    u'''Проверяем, являеться ли пользователь слушателем на циклах МЗ.'''

    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)
    c1 = db1.createStatement()
    countuser = c1.executeQuery("select count(*) from dbVector.journals.requests where sid='" + sid + "' and cycle_event_id in ('f4ad0490-7ce9-11e3-b756-f3e7cbea0fad','214750dc-7cea-11e3-945c-8f09fc08d85c') and status_id='bcb486fa-7c79-11e3-916e-93eeee940426'")
    countuser.next()
    numrows_1 = countuser.getInt(1)
    c1.close()
    c2=db1.createStatement()
    countuser=c2.executeQuery("""select count(*) from dbVector.fuved.person_cycleAsEvent_eok pce inner join dbVector.dbo.usersAuthServerFUV uaf on uaf.personUid=pce.personid where uaf.uid='""" + sid + """' and cycleid in ('f4ad0490-7ce9-11e3-b756-f3e7cbea0fad','214750dc-7cea-11e3-945c-8f09fc08d85c')""")
    countuser.next()
    numrows_2=countuser.getInt(1)
    c2.close()
    db1.close()

    if numrows_1 > 0 or numrows_2 > 0:
        return True
    else:
        return False

def userOnAnyCycle(sid):
    u'''Проверяем, является ли пользователь зачисленным на какой-либо цикл.'''

    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)
    c1 = db1.createStatement()
    countuser = c1.executeQuery("select count(*) from dbVector.journals.requests where sid='" + sid + "' and status_id='bcb486fa-7c79-11e3-916e-93eeee940426'")
    countuser.next()
    numrows_1 = countuser.getInt(1)
    c1.close()
    c2 = db1.createStatement()
    countuser = c2.executeQuery("select count(*) from dbVector.fuved.person_cycleAsEvent_eok pce inner join dbVector.dbo.usersAuthServerFUV uaf on uaf.personUid=pce.personid where uaf.uid='" + sid + "' and pce.roleid = 'listener' ")
    countuser.next()
    numrows_2 = countuser.getInt(1)
    c2.close()
    db1.close()

    if numrows_1 > 0 or numrows_2 > 0:
        return True
    else:
        return False

def userOnFreeCycle(sid):
    u'''Проверяем, заполнил ли пользователь мин. рег. данные для доступа к свободному циклу.'''

    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)
    c1 = db1.createStatement()
    #countuser = c1.executeQuery("select count(*) from journals.reg_data rd inner join journals.education ed ON rd.uid=ed.reg_data_id inner join journals.job j ON j.reg_data_id=rd.uid where rd.sid='" + sid + "' and rd.surname IS NOT NULL and rd.name IS NOT NULL and rd.patronymic IS NOT NULL and rd.birth_year IS NOT NULL and rd.sex IS NOT NULL and j.speciality_id IS NOT NULL and ed.series IS NOT NULL and ed.number IS NOT NULL and ed.name IS NOT NULL")
    regdata = c1.executeQuery("select uid from dbVector.journals.reg_data rd where rd.sid='" + sid + "' and rd.surname IS NOT NULL and rd.name IS NOT NULL and rd.patronymic IS NOT NULL and rd.birth_year IS NOT NULL and rd.sex IS NOT NULL")
    if regdata.next():
        regdata_id = regdata.getObject('uid')
        c2 = db1.createStatement()
        eddata = c2.executeQuery("select count(*) from dbVector.journals.education ed where ed.reg_data_id='" + regdata_id + "' and ed.certificate_type_id='91d87cda-9141-11e2-aff1-078732cdf002' and ed.name IS NOT NULL and ed.number IS NOT NULL and ed.series IS NOT NULL")
        eddata.next()
        numrows = eddata.getInt(1)
        c2.close()
        if numrows > 0:
            eddata_ok = True
        else:
            return False
        c3 = db1.createStatement()
        jobdata = c3.executeQuery("select count(*) from dbVector.journals.job j where j.reg_data_id='" + regdata_id + "' and j.speciality_id IS NOT NULL")
        jobdata.next()
        numrows = jobdata.getInt(1)
        if numrows > 0:
            jobdata_ok = True
        else:
            return False

        if eddata_ok and jobdata_ok:
            return True

    else:
        return False

    c1.close()
    db1.close()




def learningButton(sid):
    u'''Кнопка Обучение имеет три режима: Обучение на цикла, Свободные материалы, Пройти упрощенную регистрацию
    для доступа к свободным материалам.'''


    if userOnAnyCycle(sid):
        # Пользователь зачислен на какой-либо цикл
        lcab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=listenercab';window.open(url,'_self');">
                            <span class="xforms-label">Обучение на циклах</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
        return [lcab, '<properties></properties>']
    elif userOnFreeCycle(sid) and not userOnAnyCycle(sid):
        # Пользователь на свободном цикле, а на обычный цикл не зачислен
        lcab = u'''<p><div style="margin-left:1px; width:270px;" class="newbutton">
                    <span class="blue xforms-trigger">
                        <span class="value" >
                            <button style="cursor: pointer; width: 100%" type="submit" onclick="var url='?userdata=listenercab';window.open(url,'_self');">
                            <span class="xforms-label">Свободные материалы</span>
                            </button>
                        </span>            
                    </span>
                </div></p>'''
        return [lcab, '<properties></properties>']
	
    else:
		lcab = ''
		properties = u'''<properties></properties>'''
        # Пользователь еще не имеет доступа ни к свободному циклу, ни к обычным
#        lcab = u'''<div class="newbutton">
#                <span class="blue xforms-trigger">
 #                   <span class="value">
  #                      <button style="width: 270px; heigth: 40px; text-align: center" onclick="gwtWebTextFunc('%s','simplereg');">
   #                         <span class="xforms-label">
    #                        Получить доступ к свободным материалам
     #                       </span>
      #                  </button>
       #             </span>            
        #        </span>
         #   </div> ''' % elementId
#        properties = u'''<properties>
 #           <event name="single_click" linkId="simplereg">
  #               <action show_in="MODAL_WINDOW">
   #                 <main_context>current</main_context>
    #                <modalwindow caption="Упрощенная регистрация" width="500" height="600" />
     #               <datapanel type="current" tab="current">
      #                  <element id="simplereg">
       #                     <add_context></add_context>
        #                </element>
#                    </datapanel>
 #               </action>
  #          </event>
   #     </properties>'''

		return [lcab, properties]


if __name__ == "__main__":
    mainproc()
