using System;
using System.Collections.Generic;
using System.Drawing;

using VirtualLab.Programming;
using VirtualLabAPI.Core.Common;
using VirtualLabAPI.Core.FieldRepresentations;
using VirtualLabAPI.Core.Numerics;
using VirtualLabAPI.Core.Modules;

public class VLModule : IVLModule {
    //seed for random phase per HFS member 
    int randomSeed = -1;
    
    //maximum phase
    double maxPhase = 1 * Math.PI;
    
    //run method
    public void Run() {
        int dummy;
        //get HFS from VL main window
        HarmonicFieldsSet hfsForSummation = Globals.ActiveDocumentHistory.BrowseLastDocuments(DocumentFilter.HarmonicFieldsSet,
                                                                                              out dummy,
                                                                                              "Select HFS for Calculation",
                                                                                              false) as HarmonicFieldsSet;
        
        //error handling
        if(hfsForSummation == null){
            return;
        }
        //init summation result
        ComplexAmplitude summationResult = null;
        
        //init random object
        Random rPhaseVal;
        //use correct seed (if seed == -1 it is chosen randomly
        if(randomSeed == -1){
            rPhaseVal = new Random();
        }else{
            rPhaseVal = new Random(randomSeed);
        }
        
        //run through all member
        for(int runMember = 0; runMember < hfsForSummation.Count; runMember++){
            //determine random phase value
            double curentRandomPhaseVal = rPhaseVal.NextDouble() * maxPhase;
            //extract current member from hfs
            ComplexAmplitude caCurrent = hfsForSummation[runMember];
            //modify phase randomly
            caCurrent *= Complex.Polar(1, curentRandomPhaseVal);
            
            if(summationResult == null){
                //if first field ==> init result
                summationResult = caCurrent;
            }else{
                //perform summation of current field
                summationResult = ComplexAmplitude.AddWithResampling(summationResult,                //field 1
                                                                     caCurrent,                      //field 2
                                                                     InterpolationMethod.SincFFT,    //interpolation method for field 1
                                                                     InterpolationMethod.SincFFT);   //interpolation method for field 2
            }
        }
        
        //if summation result is available
        if(summationResult != null){
            //show field
            Globals.DataDisplay.ShowDocument(summationResult, "Coherent summation");
        }
    }
}
