package service

import (
	"encoding/json"
	"fmt"
	"path/filepath"
	"strings"

	"be.ems/src/framework/ssh"
	"be.ems/src/modules/network_data/model"
	neService "be.ems/src/modules/network_element/service"
	systemService "be.ems/src/modules/system/service"
)

// 实例化数据层 Backup 结构体
var NewBackup = &Backup{
	BACKUP_DIR:       "/usr/local/omc/backup",
	neInfoService:    neService.NewNeInfo,
	sysConfigService: systemService.NewSysConfigImpl,
}

// Backup 备份相关 服务层处理
type Backup struct {
	BACKUP_DIR       string                       // 备份目录
	neInfoService    *neService.NeInfo            // 网元信息服务
	sysConfigService *systemService.SysConfigImpl // 参数配置服务
}

// FTPConfigUpdate 更新FTP配置信息
func (r Backup) FTPConfigUpdate(value, updateBy string) int64 {
	cfg := r.sysConfigService.SelectConfigByKey("neData.backupDataFTP")
	if cfg.ConfigID == "" {
		return 0
	}
	cfg.ConfigValue = value
	cfg.UpdateBy = updateBy
	return r.sysConfigService.UpdateEncryptValue(cfg)
}

// FTPConfigInfo 获取FTP配置信息
func (r Backup) FTPConfigInfo() model.BackupDataFTP {
	info := model.BackupDataFTP{}
	// 获取配置
	cfg := r.sysConfigService.FindByKeyDecryptValue("neData.backupDataFTP")
	if cfg.ConfigID != "" && cfg.ConfigValue != "" {
		if err := json.Unmarshal([]byte(cfg.ConfigValue), &info); err != nil {
			return info
		}
	}
	return info
}

// FTPPushFile 推送文件到FTP
func (r Backup) FTPPushFile(localFilePath, tag string) error {
	cfgData := r.FTPConfigInfo()
	if !cfgData.Enable {
		return fmt.Errorf("setting remote backup ftp is disabled")
	}

	connSSH := ssh.ConnSSH{
		User:     cfgData.Username,
		Password: cfgData.Password,
		Addr:     cfgData.ToIp,
		Port:     cfgData.ToPort,
		AuthMode: "0",
	}
	sshClient, err := connSSH.NewClient()
	if err != nil {
		return err
	}
	defer sshClient.Close()
	// 网元主机的SSH客户端进行文件传输
	sftpClient, err := sshClient.NewClientSFTP()
	if err != nil {
		return err
	}
	defer sftpClient.Close()

	remotePath := strings.Replace(localFilePath, r.BACKUP_DIR, tag, 1)
	remotePath = filepath.Join(cfgData.Dir, remotePath)
	// 复制到远程
	if err = sftpClient.CopyFileLocalToRemote(localFilePath, remotePath); err != nil {
		return fmt.Errorf("error uploading file")
	}
	return nil
}
