/*=========================================================================
 
  Program:   Orbit Visualization Tool
  Source:    $Source: /stor/devel/ovt2g/ovt/object/SatelliteModule.java,v $
  Date:      $Date: 2001/04/16 18:09:06 $
  Version:   $Revision: 1.25 $
 
 
Copyright (c) 2000 OVT Team (Kristof Stasiewicz, Mykola Khotyaintsev,
Yuri Khotyaintsev)
All rights reserved.
 
Redistribution and use in source and binary forms, with or without
modification is permitted provided that the following conditions are met:
 
 * No part of the software can be included in any commercial package without
written consent from the OVT team.
 
 * Redistributions of the source or binary code must retain the above
copyright notice, this list of conditions and the following disclaimer.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT OR
INDIRECT DAMAGES  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE.
 
OVT Team (http://ovt.irfu.se)   K. Stasiewicz, M. Khotyaintsev, Y.
Khotyaintsev
 
=========================================================================*/

package ovt.object;

import vtk.*;

import ovt.*;
import ovt.beans.*;
import ovt.mag.*;
import ovt.util.*;
import ovt.event.*;
import ovt.datatype.*;
import ovt.interfaces.*;

import java.beans.*;
import java.awt.*;
import javax.swing.*;

/**
 * This  that should be added
 * to { @link ovt.datatypes.Sat }.
 * @author Mykola Khotyaintsev
 * @see ovt.datatypes.AbstractSatModule
 */
public class SatelliteModule extends SingleActorSatModule {
    
    protected double[] spinActorPos = new double[3];
    private float satRadius=0.05f;
    private boolean actorIsArrow;
    public static final int DEBUG = 10;
 
    public SatelliteModule(Sat satellite) {
        super(satellite, "Sat");
        setColor(Color.blue);
        setIcon(new ImageIcon(OVTCore.getImagesDir() + "satellite.gif"));
    }
    
    //added by kono
    public float getSatRadius(){
        return satRadius;
    }
    
    public void setSatRadius(float sR){
        satRadius = sR;
        update();
    }
    
    public boolean isSpinActorAvailable(){
        return getSat().isSpinAvailable();
    }
    
  /*
  protected void update() {
    if (isVisible()) {
      double[] a = getPosition();
      if (a != null) {
        // update actors position
        //getActor().SetPosition(a[0], a[1], a[2]);
        hide();
        satActor=createSatActor();
        satActor.SetPosition(a[0], a[1], a[2]);
   
        //System.out.println(getName() + " pos: " + a[0]+"\t"+a[1]+"\t"+a[2]);
        // add actor if it is not in renderer
        show();
      }
    } else { // no position data availible - hide actor
      //System.out.println("Trying to hide actor!!! ");
      hide();
    }
  }
   
  private vtkActor createSatActor() {
   
    vtkActor actor = createSatAsArrow();
     if(actor==null)
        actor=createSatAsSphere();
    if (actor != null) {
        float[] rgb = ovt.util.Utils.getRGB(getColor());
        actor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2]);
    }
    return actor;
}*/
    
    private void createSatAsSphere(){
        // create sphere geometry
        actor = new vtkActor();
        vtkSphereSource sphere = new vtkSphereSource();
        sphere.SetRadius(getSatRadius());
        
        sphere.SetThetaResolution(8);
        sphere.SetPhiResolution(8);
        
        // map to graphics library
        vtkPolyDataMapper map = new vtkPolyDataMapper();
        map.SetInput(sphere.GetOutput());
        
        // actor coordinates geometry, properties, transformation
        actor.SetMapper(map);
        float[] rgb = ovt.util.Utils.getRGB(getColor());
        actor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2]);
        actor.SetScale(scale);
        actorIsArrow = false;
    }
    
    private void createSatAsArrow() {
        if (isSpinActorAvailable()) {
            double[] spinVect = getSat().getSpinVectorRate();
            if (spinVect != null) {
                
                vtkPolyData polyData = new vtkPolyData();
                vtkPoints points = new vtkPoints();
                vtkVectors vectors = new vtkVectors();
                
                points.InsertNextPoint(0, 0, 0);
                //vectors.InsertNextVector(spinVect[0],spinVect[1],spinVect[2]);
                vectors.InsertNextVector(0, 0, 1);
                
                polyData.SetPoints(points);
                polyData.GetPointData().SetVectors(vectors);
                
                vtkConeSource cone = new vtkConeSource();
                cone.SetResolution(2);
                
                vtkGlyph3D glyph = new vtkGlyph3D();
                glyph.SetInput(polyData);
                glyph.SetSource(cone.GetOutput());
                glyph.SetVectorModeToUseVector();
                glyph.OrientOn();
                
                //glyph.SetScaleFactor(0.04);
                glyph.SetScaleFactor(1);
                
                vtkPolyDataMapper mapper = new vtkPolyDataMapper();
                mapper.SetInput(glyph.GetOutput());
                
                actor = new vtkActor();
                actor.SetMapper(mapper);
                float[] rgb = ovt.util.Utils.getRGB(getColor());
                actor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2]);
                actor.SetScale(scale/10);
                actorIsArrow = true;
            }
        }
    }
    
    public void validate() {
        createSatAsArrow();
        if (actor == null) createSatAsSphere();
        super.validate();
    }
    
    public void show() {
        if (actorIsArrow != isSpinActorAvailable()) invalidate();
        if (!isValid()) validate();
        double[] r = getPosition();
        if (actor != null) actor.SetPosition(r);
        if (actorIsArrow) rotate();
        super.show();
    }
    
    
    public void rotate() {
        double[] z = {0, 0, 1};
        double[] spinv = getSat().getSpinVectorRate(); // Z-axis
        double[] rot_axis = Vect.crossn(spinv, z);
        double angle = Vect.angleOf2vect(spinv, z);
        //System.out.println("Angle = " + new java.text.DecimalFormat().format(angle));
        //spinv[0] = Math.random();
        Log.log("Spin Vector = " + Vect.toString(spinv), DEBUG);
        //actor.SetOrientation(spinv[0], spinv[1], spinv[2]);
        actor.SetOrientation(0, 0, 0);
        actor.RotateWXYZ(Utils.toDegrees(angle), rot_axis[0], rot_axis[1], rot_axis[2]);
    }
    
    public void update() {
        if (isVisible() && isEnabled()) {
            if (actorIsArrow != isSpinActorAvailable()) {
                invalidate();
                hide();
                show();
            }
            double[] r = getPosition();     // here returns null!!!
            if (actor != null) {
                actor.SetPosition(r[0], r[1], r[2]);
                if (actorIsArrow) rotate();
            }
        }
    }
    
    public void timeChanged(TimeEvent e) {
        update();
    }
    
    public void coordinateSystemChanged(CoordinateSystemEvent evt) {
        update();
    }
    
    public Descriptors getDescriptors() {
        if (descriptors == null) {
            try {
                descriptors = super.getDescriptors();
                
                BasicPropertyDescriptor pd = new BasicPropertyDescriptor("scale", this);
                pd.setLabel("Size");
                pd.setDisplayName(getParent().getName() + " size");
                SliderPropertyEditor sliderEditor = new SliderPropertyEditor(pd);
                addPropertyChangeListener("scale", sliderEditor);
                sliderEditor.makeExponential(8, 7);
                sliderEditor.addGUIPropertyEditorListener(new GUIPropertyEditorListener() {
                    public void editingFinished(GUIPropertyEditorEvent evt) {
                        Render();
                    }
                });
                pd.setPropertyEditor(new WindowedPropertyEditor(sliderEditor, getCore().getXYZWin()));
                descriptors.put(pd);
                
            } catch (IntrospectionException e2) {
                System.out.println(getClass().getName() + " -> " + e2.toString());
                System.exit(0);
            }
        }
        return descriptors;
    }
    
    private double scale = 1;
    
    public double getScale() {
        return this.scale;
    }
    
    public void setScale(double scale) {
        //System.out.println("new scale: " + scale);
        double oldScale = scale;
        this.scale = scale;
        if (actor != null) {
            if (actorIsArrow) actor.SetScale(scale/10);
            else actor.SetScale(scale);
        }
        firePropertyChange("scale", new Double(oldScale), new Double(scale));
    }
    
}
