# -*- coding: utf-8 -*-
# calchar.py

import numpy as np
import sol.farfield

# input impedance or cross section
def calc(
    Ne, Nfreq, Freq, Nfeed, E_posc, E_lng, E_tan, E_ifeed, E_feed, Planewave, Iground, Z0, Xc):

    Zin = []
    Rcs = []
    if Nfeed > 0:
        Zin = _zinput(Ne, Nfreq, Nfeed, E_ifeed, E_feed, Xc)
    else:
        Rcs = _cross_section(Ne, Nfreq, Freq, Nfeed, E_posc, E_lng, E_tan, E_ifeed, E_feed, Planewave, Iground, Z0, Xc, Zin)

    return Zin, Rcs

# input impedance (private)
def _zinput(Ne, Nfreq, Nfeed, E_ifeed, E_feed, Xc):
    # alloc
    Zin = np.zeros((Nfeed, Nfreq), complex)

    ifeed = 0
    for ie in range(Ne):
        if E_ifeed[ie] > 0:
            vin = E_feed[ie, 0] * np.exp(1j * np.deg2rad(E_feed[ie, 1]))
            for ifreq in range(Nfreq):
                Zin[ifeed, ifreq] = vin / Xc[ifreq, ie]
            ifeed += 1

    return Zin

# cross section : BCS/FCS (private)
def _cross_section(Ne, Nfreq, Freq, Nfeed, E_posc, E_lng, E_tan, E_ifeed, E_feed, Planewave, Iground, Z0, Xc, Zin):
    theta = Planewave[0]
    phi   = Planewave[1]

    # alloc
    Rcs = np.zeros((2, Nfreq), float)

    for ifreq, freq in enumerate(Freq):
        ffctr = sol.farfield.factor(Ne, Nfeed, E_ifeed, E_feed, Zin, Z0, ifreq, 0)
        # BCS
        _, pfar = sol.farfield.field(ifreq, freq, theta, phi, ffctr, Ne, E_posc, E_lng, E_tan, Iground, Xc)
        Rcs[0, ifreq] = pfar[0]
        # FCS
        _, pfar = sol.farfield.field(ifreq, freq, 180 - theta, phi + 180, ffctr, Ne, E_posc, E_lng, E_tan, Iground, Xc)
        Rcs[1, ifreq] = pfar[0]
    
    return Rcs
