package com.judong.chuanyiserver.service.impl;

import com.judong.chuanyiserver.dao.ConnectDao;
import com.judong.chuanyiserver.entity.ServerInformation;
import com.judong.chuanyiserver.enums.ResultEnum;
import com.judong.chuanyiserver.exception.CustomException;
import com.judong.chuanyiserver.service.ConnectService;
import com.judong.chuanyiserver.util.*;
import lombok.extern.slf4j.Slf4j;
import org.jinterop.dcom.common.JIException;
import org.openscada.opc.dcom.da.OPCSERVERSTATE;
import org.openscada.opc.lib.common.AlreadyConnectedException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.UnknownHostException;
import java.util.concurrent.Executors;

@Service
@Transactional
@Slf4j
public class ConnectServiceImpl implements ConnectService {

    @Autowired
    private ConnectDao connectDao;
    @Autowired
    private UserUtil userUtil;

    @Override
    public Result testConnect(ServerInformation serverInformation) throws AlreadyConnectedException, JIException, UnknownHostException {
        switch (serverInformation.getAgreementType()) {
            case ConstantStr.OPC_DA:
                if(Blank.isEmpty(serverInformation.getIpUserName(),serverInformation.getIpPassword())){
                    return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), ResultEnum.REQUEST_WRONGPARAMS.getRespMsg());
                }
                return OpcServerDaUtil.opcDaTestConnect(serverInformation);
            case ConstantStr.OPC_UA:
                return OpcServerDaUtil.opcDaTestConnect(serverInformation);
            default:
                throw new CustomException(ResultEnum.NOT_FOUND.getRespCode(), "没有此协议类型");
        }
    }

    @Override
    public synchronized Result saveConnect(ServerInformation serverInformation) {
        String userId = userUtil.getCurrentUserId();
        serverInformation.setUserId(userId);
        serverInformation.setIpPassword(RSAUtil.encryptByPublic(serverInformation.getIpPassword(), RSAUtil.PUBLIC_KEY));
        ServerInformation si = connectDao.getServerInformation(userId, serverInformation.getIpAddress());
        if (Blank.isNotEmpty(si)) {
            return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该用户下此ip已被使保存，请更换其他ip");
        }
        if (connectDao.saveConnect(serverInformation) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "保存连接失败");
        }
        return Result.ok("保存连接成功");
    }

    @Override
    public Result selectAllConnect() {
        return Result.ok(connectDao.selectAllConnect(userUtil.getCurrentUserId()));
    }

    @Override
    public synchronized Result editConnect(ServerInformation serverInformation) {
        String userId = userUtil.getCurrentUserId();
        serverInformation.setIpPassword(RSAUtil.encryptByPublic(serverInformation.getIpPassword(), RSAUtil.PUBLIC_KEY));
        ServerInformation si = connectDao.getServerInformationEdit(serverInformation.getId(), userId, serverInformation.getIpAddress());
        if (Blank.isNotEmpty(si)) {
            return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该用户下此ip已被使保存，请更换其他ip");
        }
        if (connectDao.editConnect(serverInformation) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "编辑连接失败");
        }
        return Result.ok("编辑连接成功");
    }

    @Override
    public synchronized Result deleteConnect(int id) {
        String userId = userUtil.getCurrentUserId();
        if (connectDao.deleteConnect(id, userId) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "删除连接失败");
        }
        return Result.ok("删除连接成功");
    }

    @Override
    public Result openConnect(int id) throws Exception {
        ServerInformation serverInformation = connectDao.getServerInformationById(id);
        if (Blank.isEmpty(serverInformation)) {
            return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
        }
        switch (serverInformation.getAgreementType()) {
            //如果协议类型为OPCDA
            case ConstantStr.OPC_DA:
                return OpcServerDaUtil.opcDaReadItemTree(serverInformation);
            default:
                throw new CustomException(ResultEnum.NOT_FOUND.getRespCode(), "没有此协议类型");
        }
    }

    @Override
    public Result readItemValue(int id, String itemName) throws Exception {
        ServerInformation serverInformation = connectDao.getServerInformationById(id);
        if (Blank.isEmpty(serverInformation)) {
            return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
        }
        //如果协议类型为OPCDA
        if (serverInformation.getAgreementType() == ConstantStr.OPC_DA) {
            return OpcServerDaUtil.opcDaReadItemValue(serverInformation, itemName);
        }
        return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
    }

}
