#include <dbAccess.h>
#include <dbAddr.h>
#include <dbDefs.h>
#include <link.h>
#include <registryFunction.h>
#include <epicsExport.h>
#include <errlog.h>
#include <aSubRecord.h>
#include <subKlys.h>

#include "pv/rpcClient.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace epics::pvData;
using namespace epics::pvAccess;

/*
 *  Read in DSTA words and individual status bits
 *  and use these to build new DSTA word
 *
 *  Inputs
 *
 *      individual DSTA bits:
 *
 *        PV       description      bit shift
 *       string                     in DSTA2
 *     ---------------------------------------
 *     a  LCL "Modulator in Local"      3
 *     b  RM  "Mod Bit 4"               4
 *     c  EVO "Mod EVOC Fault"          5
 *     d  EVC "Mod EOLC Fault"          6
 *     e  TOC "Mod Trigger Overcurrent" 7
 *     f  HVO "Mod HV ON"               8
 *     g  MOD "Mod 'EXTERNAL' Fault"    9
 *     h  FLK "Mod FAULT Lockout"       10
 *     i  HVR "Mod HV Ready"            11
 *     j  MOK "Mod Interlocks Complete" 12
 *     k  KHD "Mod KLYS Heater Delay"   13
 *     l  VVS "Mod VVS Voltage Fault"   14
 *     m  MPF "Mod CONTROL Power Fault" 15
 *     n  VET "Veto Asserted on Accelerate" 16
 *     o  VED "Veto Assertion Disabled" 17
 *     p   TV  "Veto Test in Progress"  18
 *     q  MTR "Mod Triggering"          19
 *
 *
 *       raw dsta:
 *
 *
 *     r  Raw DSTA
 *
 *  Outputs
 *
 *      a   DSTA, 2 element array
 */

long
subKlysDsta(struct aSubRecord *psub)
{
int a = *(epicsUInt32 *)psub->a;
int b = *(epicsUInt32 *)psub->b;
int c = *(epicsUInt32 *)psub->c;
int d = *(epicsUInt32 *)psub->d;
int e = *(epicsUInt32 *)psub->e;
int f = *(epicsUInt32 *)psub->f;
int g = *(epicsUInt32 *)psub->g;
int h = *(epicsUInt32 *)psub->h;
int i = *(epicsUInt32 *)psub->i;
int j = *(epicsUInt32 *)psub->j;
int k = *(epicsUInt32 *)psub->k;
int l = *(epicsUInt32 *)psub->l;
int m = *(epicsUInt32 *)psub->m;
int n = *(epicsUInt32 *)psub->n;
int o = *(epicsUInt32 *)psub->o;
int p = *(epicsUInt32 *)psub->p;
int q = *(epicsUInt32 *)psub->q;

epicsUInt32 r[2];
epicsUInt32 dsta[2];

epicsUInt32 mask_clear = 0xFFFF8;
epicsUInt32 mask_set = (a<<3)|(b<<4)|(c<<5)|(d<<6)|(e<<7)|(f<<8)|(g<<9)|
		       (h<<10)|(i<<11)|(j<<12)|(k<<13)|(l<<14)|(m<<15)|
		       (n<<16)|(o<<17)|(p<<18)|(q<<19);

	memcpy( r, (epicsUInt32 *)psub->r, sizeof( r ) );

	dsta[0] = r[0];
	dsta[1] = (r[1] & ~mask_clear) | mask_set;

	memcpy( (epicsUInt32 *)psub->vala, dsta, sizeof( dsta ) );

	return 0;
}

/*=============================================================================

  Name: recordTestReadRpcFloatPv

  Abs:  Broadcasts the value of a floating-point RPC PV through CA

  Args: Type                Name        Access     Description
        ------------------- ----------- ---------- ----------------------------
        subRecord *         psub        read/write pointer to subroutine record

  Rem:  Input:
        --------
        INPA - RPC PV name

        Output:
        --------
        VALA - value of RPC PV

  Side: None

  Ret:  long
          0 - Successful
         -1 - for invalid RPC PV name
         -2 - for invalid RPC PV value

==============================================================================*/

static long subKlysReadRpcFloatPv(aSubRecord *psub)
{
  long status = OK;
  char rpc_pv[PVNAME_STRINGSZ];
  double rpc_pv_val = 0;
  *(double *)psub->vala = 0.0;

  // Get RPC PV from input A
  strcpy(rpc_pv, (char *)psub->a);
  if (*rpc_pv == 0) {
    // Return error if PV name is blank
    std::cout << "Error: empty PV name" << std::endl;
    return ERROR;
  }

  // Form channelRPC request
  PVStructurePtr argument;
  {
    FieldBuilderPtr builder(getFieldCreate()->createFieldBuilder());
    builder = builder->setId("epics:nt/NTURI:1.0")
            ->add("scheme", pvString)
            ->add("authority", pvString)
            ->add("path", pvString)
            ->addNestedStructure("query");

    StructureConstPtr type(builder->endNested()
                                ->createStructure());
    argument = getPVDataCreate()->createPVStructure(type);

    argument->getSubFieldT<PVString>("scheme")->put("pva");
    argument->getSubFieldT<PVString>("path")->put(rpc_pv);
    PVStructurePtr query(argument->getSubFieldT<PVStructure>("query"));
  }

  // Issue channelRPC request
  PVStructure::shared_pointer result;
  try
  {
    RPCClient::shared_pointer client = RPCClient::create(rpc_pv);
    result = client->request(argument, TIMEOUT);
  } catch (std::exception &e)
  {
    // Return error if RPC PV get fails
    std::cout << "Error: " << rpc_pv << " - " << e.what() << std::endl;
    return ERROR;
  }

  // Extract float value from result
  try
  {
    rpc_pv_val = result->getSubFieldT<PVScalar>("value")->getAs<float>();
  } catch (std::exception &e)
  {
    // Return bad if value field is missing or float conversion fails
    std::cout << "Error: " << rpc_pv << " - " << e.what() << std::endl;
    return BAD;
  }

  *(double *)psub->vala = rpc_pv_val;
  return status;
}

epicsRegisterFunction(subKlysDsta);
epicsRegisterFunction(subKlysReadRpcFloatPv);
