# from ldap3 import Server,Connection,AUTO_BIND_NO_TLS,SUBTREE,ALL_ATTRIBUTES,core
from cms.common import util
from dataAccess import dataAccess


def do_login(request, syain_id, password):
    db_access = dataAccess.DBAccess()
    syainmail = syain_id + '@typical.co.jp'
    # try:

    m_syain = db_access.select_row(
        "select m_syain_mail.SYAINCODE"
        " from m_syain_mail"
        " inner join m_syain"
        "   on  m_syain_mail.SYAINCODE = m_syain.SYAINCODE"
        "   and m_syain.DELETEFLAG = 0"
        " where Mail_Address = '" + syainmail + "'")

    m_kbn_meisyo = db_access.select_row("select name From m_kbnmeisyo where kbn = 5")

    err_message = input_check(syain_id, password, m_syain, m_kbn_meisyo["name"])
    if err_message is not None:
        return err_message

    # domain = syain_id + "@typical.local"

    # 認証 2018.08.24 外常駐社員向けにログイン認証を変更
    # con = Connection(
    # Server('ldap://171.2.1.1', 389)
    # , user=domain
    # , password=password
    # , check_names=True
    # , read_only=True
    # , auto_bind=AUTO_BIND_NO_TLS)

    # 属性情報を抽出
    # con.search(
    # search_base='OU=employee,DC=typical,DC=local'
    # , search_filter='(&(userPrincipalName=' + domain + '))'
    # , search_scope=SUBTREE
    # , attributes=['description'])
    # user_id = con.response[0]['attributes']['description'][0]
    # request.session.set_expiry(0)
    # request.session['userId'] = user_id

    # create_check_period()

    # except (core.exceptions.LDAPBindError) as e:
    # return "ログイン認証に失敗しました。（3回以上間違えるとロックされます）"

    request.session.set_expiry(0)
    request.session['userId'] = str(m_syain["SYAINCODE"])

    create_check_period()
        
        
def input_check(syain_id, password, m_syain, login_password):
    if syain_id == "":
        return "ユーザ名が入力されていません。"

    if password == "":
        return "パスワードが入力されていません。"

    if m_syain == None:
        return "ユーザ名が不正です。"

    if password != login_password:
        return "パスワードが不正です。"


def create_check_period():
    db_access = dataAccess.DBAccess()
    now_date = util.now_datetime().strftime('%Y/%m/%d')

    check_list_kbn = db_access.select_rows(
        "select kbnKey, name from m_kbnmeisyo where kbn = 1")

    # チェックリスト期間マスタが存在しない場合、作成する
    for row in check_list_kbn:
        check_period_cnt = db_access.select_row(
            "select count(*) as cnt"
            " from m_checkperiod"
            " where checkKbn = " + str(row["kbnKey"]) +
            " and stDate <= '" + now_date + "'"
            " and edDate >= '" + now_date + "'")
        if check_period_cnt["cnt"] == 0:
            check_preiod = db_access.select_row(
                "select value"
                " from m_kbnmeisyo "
                " where kbn = 3"
                " and kbnKey = " + str(row["kbnKey"]))
            # 開始日算出
            preiod = check_preiod["value"]
            if preiod == 1:
                st_date = util.now_datetime().strftime('%Y/%m/01')
            else:
                now_year = util.now_datetime().year
                now_month = util.now_datetime().month
                calc_month = 4

                if now_month < 4:
                    now_month += 12

                for idx in range(7):
                    if calc_month <= now_month <= calc_month + preiod - 1:
                        if calc_month > 12:
                            calc_month = calc_month % 12

                        if calc_month + preiod - 1 > 12:
                            now_year -= 1

                        st_date = str(now_year) + "/" + format(calc_month, '02d') + "/01"
                        break

                    calc_month += preiod

            # チェックリスト期間マスタの登録
            db_access.regist_db(
                "insert into m_checkperiod values ("
                + str(row["kbnKey"])
                + ",'" + st_date + "'"
                + "," + "DATE_ADD(DATE_ADD('" + st_date + "', INTERVAL " + str(preiod) + " MONTH), INTERVAL -1 DAY)"
                + ",0"
                ")")

    db_access.commit()
