local obj = {}

local ss = analiz.libs.serv

ss.l("load FPatch1979")

local CCR_PWD = "plib_aml"

obj.moved_files = {}
obj.patch = {id = "FPatch1979"}

function obj:prepare(ctx)

    ctx:get_options("global_oracle_setting_local",
                    "_root_\\Namechecking\\p.Secco processing nodes\\std.oracle\\lexEngine\\AnalizServices\\.Local\\global_setting_local.lua",
                    {global_name = "global_oracle_setting_local"})

    ctx:get_options("global_prospero_setting",
                    "_root_\\Internal\\.Local\\global_prospero_setting.lua",
                    {global_name = "global_prospero_setting"})

    ctx:get_options("system_configs_v3",
                    "_root_\\Internal\\.Local\\system_configs_v3.lua",
                    {global_name = "system_configs_v3"})

    ctx:get_options("global_prospero_system",
                    "_root_\\Internal\\.Local\\system.lua",
                    {global_name = "global_prospero_system"})

    if ctx.plibs == nil then ctx.plibs = {} end
    if ctx.plibs.ccr == nil then

        ctx.plibs.ccr = CreatePlibExportImportServ({pwd = CCR_PWD})
        if ctx.plibs.ccr == nil then
            ss.l("create ctx.plibs.ccr:failed FPatch1979")
            ss.a(11)
        end
    end

end

local function fix_(val)
    if val:find("'") == nil then return val end
    return ss.ReplaceValue(val, "'", "''")
end

local function add_org_param_(profile, name, val)
    ss.s("tmp_profile", fix_(profile))
    ss.s("tmp_email", fix_(val))
    ss.e("echo EXEC_SQL PLIB  exec ADD_ORG_PARAM '$(tmp_profile)','" .. name ..
             "','$(tmp_email)'")
    ss.e("EXEC_SQL PLIB  exec ADD_ORG_PARAM '$(tmp_profile)','" .. name ..
             "','$(tmp_email)'")
end
-- -------------------------------------------
local function install_txm_email_(item)
    if item.profile ~= nil then
        ss.l("install email: " .. item.email .. " for profile:" .. item.profile)
        add_org_param_(item.profile, 'EMAIL', item.email)
        return
    end
    ss.l("install email: " .. item.email .. " for bank:" .. item.bank_id)

    local sql = [[declare @ProfileName VARCHAR(255) = NULL,
     @bank_id int=]] .. item.bank_id .. [[

	select @ProfileName = ProfileName
	  from OrgClients where F_BANK_ID= @bank_id


	if @ProfileName is NULL
	 begin
	select @ProfileName = ProfileName
	  from TestOrgClients where F_BANK_ID= @bank_id
	end

	if @ProfileName is not NULL
        begin
          exec ADD_ORG_PARAM @ProfileName,'TXM_EMAIL',']] .. fix_(item.email) .. [['
        end
]]
    ss.s("tmp_sql", sql)
    ss.e("echo EXEC_SQL PLIB  $(tmp_sql)'")
    ss.e("EXEC_SQL PLIB  $(tmp_sql)")

end
-- -------------------------------------------
local function FindPwds_(pwds, name)
    for i = 1, #pwds do if pwds[i].name == name then return i end end
    return nil
end

-- -------------------------------------------
function obj:install_pwd_(ctx, p)
    do
        ss.l("add global_prospero_system")
        local opt = ctx.local_options.global_prospero_system
        local obj = opt:getObj()

        if obj.pwds == nil then obj.pwds = {} end

        local index = FindPwds_(obj.pwds, p.local_pwd_name)
        ss.l("update_pwd:" .. p.local_pwd_name .. " index:" ..
                 ss.def(index, "nil"))
        if index ~= nil then
            ss.l("modify " .. p.local_pwd_name .. " to global_prospero_system")
            ss.l("old.value:" .. ss.toJson(obj.pwds[index]))
            obj.pwds[index] = {
                name = p.local_pwd_name,
                conn = {
                    dsn = p.dsn,
                    user = p.user,
                    pwd = p.pwd,
                    org = ss.def(p.org, "")
                }
            }
        else
            ss.l("add " .. p.local_pwd_name .. " to global_prospero_system")
            obj.pwds[#obj.pwds + 1] = {
                name = p.local_pwd_name,
                conn = {
                    dsn = p.dsn,
                    user = p.user,
                    pwd = p.pwd,
                    org = ss.def(p.org, "")
                }
            }
        end

        opt:dirty()
    end

    ss.l("obj:install.:install_sys.pwd...ok")
end

--------------------------------------------------------------------------

---------------------------------------------
function weak_write_to_ini_(ctx, op)

    local function keyExists_(fn, ii)
	ss.l("keyExists_")
	ss.tprint(ii)
	ss.l("_________________")
        local undef = "{9C49236D-FD4F-42F1-A3AC-FE533E6944F6}"
        ss.s("tmp_fn", fn)
        ss.s("tmp_sec", ii.sec)
        ss.s("tmp_key", ii.key)
        ss.s("tmp_def", undef)
        ss.e("LOAD_PARAM_FROM_INI_FILE_DEFAULT $(tmp_fn) tmp $(tmp_sec) $(tmp_key) $(tmp_def)")
        local val = ss.g("tmp")
        local isdef = val ~= undef
         if not(isdef) then val = "<not found this key>" end
        ss.l("check key:"..ii.sec.."."..ii.key.."="..val..":"..fn)
        return
    end

    local function write_(fn, ii)
	ss.l("write_")
        ss.s("tmp_fn", fn)
        ss.s("tmp_sec", ii.sec)
        ss.s("tmp_key", ii.key)
        ss.s("tmp_val", ii.value)
        ss.e("echo SAVE_TO_INI_FILE $(tmp_fn) $(tmp_val) $(tmp_sec) $(tmp_key)")
        ss.e("SAVE_TO_INI_FILE $(tmp_fn) $(tmp_val) $(tmp_sec) $(tmp_key)")
    end

    local fn = ss.ReplaceValue(op.config, "_root_", ctx.root_dir)

    for k, v in pairs(op.params) do

        if not (keyExists_(fn, v))
        then write_(fn, v)
        else
	  ss.l("skip write.key "..v.key)
        end
    end

end
-- -------------------------------------------
-- -------------------------------------------

function obj:install_plib_package(ctx, link)
    local ret, emessage = ctx.plibs.ccr:CheckModel(link.plib)
    if emessage ~= "" then
        ss.l("Failed check model:" .. link.plib)
        ss.l("Failed:" .. emessage)
        ss.a(101)
    end
    if link.overwrite == true and ret then
        ss.l("CCR model:" .. link.plib .. ": overwrite package")
        ret = false
    end

    if ret then
        ss.l("CCR model:" .. link.plib .. ": found.Skip install")
        return
    end

    ss.l("install CCR model:" .. link.plib)

    local import_fn = self.patch.full_dir .. "\\" .. link.packagename
    ss.l("import_fn:" .. import_fn)
    local ret, ret_ex, emessage = ctx.plibs.ccr:ImportModel(import_fn,
                                                            {overwrite = "1"})
    ss.l("install.ret:" .. ret)
    ss.l("install.ret_ex:" .. ret_ex)
    if emessage ~= "" then
        ss.l("Failed import model:" .. link.plib)
        ss.l("file:" .. import_fn)
        ss.l("emessage:" .. emessage)
        ss.a(101)
    end
    local ret, emessage = ctx.plibs.ccr:FindModelID(link.plib)

    ss.l(emessage)
    ss.l(link.plib)
    if ret == "" then
        ss.l("failed.model " .. link.plib .. " not found after import")
        ss.a(11)
    end
end
-- -------------------------------------------

function obj:install(ctx)
    ss.l("obj:install.p1979")
    local p1979 = patchs_cfg.p1979
    if p1979 == nil then
    	ss.l("failed:patchs_cfg.p1979 is nil")
        ss.a(11)
    end



obj:install_plib_package(ctx, p1979.plibmodels.BTV_TM_base_model)
obj:install_plib_package(ctx, p1979.plibmodels.Mercantil_TM_base_model)
end

return obj

