#-*- coding: utf-8 -*-

"""
code pour la fenêtre principale de pysatellites
"""

licence="""
    the file mainWindow.py is part of the package pysatellites.
    
    Copyright (C) 2007-2008 Jean-Baptiste Butet <ashashiwa@gmail.com>,
              (C) 2007-2008 Georges Khaznadar <georgesk@ofset.org>
    

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import sys, os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from glob import glob
from UI_pysat  import Ui_MainWindow
from traj_satellite  import Trajectoire
from math import pi, cos, sin, fabs
from astres import astreNom
from point import Point
from matplotlib_widget import MyMplCanvas
from repertoire import repertoire
from video import Cinema
import flottant as flottant
from debug import Debug

class StartQT4(QMainWindow):
    def __init__(self, parent, rep=None , debugger=Debug(1), app=None):
        QMainWindow.__init__(self)
        QWidget.__init__(self, parent)
        self.debug=debugger
        self.app=app
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        if rep == None:
            self.rep=repertoire(sys.argv[0])
        else:
            self.rep=rep
        self.trajectoire = Trajectoire(self.ui.afficheur, 6400, self, debugger=self.debug)
        self.initAstres()
        self.ui.masse_astre.setText(QApplication.translate("MainWindow", "6x10^24", None, QApplication.UnicodeUTF8))
        self.ui.rayon_astre.setText(QApplication.translate("MainWindow", "6400", None, QApplication.UnicodeUTF8))
        os.chdir(self.rep.chemin("defaut"))
        self.image_sat=QPixmap("icones/sat_mini.gif")
        self.connexions_signaux()
        self.placeDepart()
        self.cinemaThread=None
        self.progress=None


    def getRayonAstre(self):
        return flottant.traduit(self.ui.rayon_astre.text())*1000

    def placeDepart(self):
        """
        place la croix à la position de départ du satellite et figure
        le vecteur vitesse
        """
        self.trajectoire.efface()
        x=0
        y=(flottant.traduit(self.ui.rayon_astre.text())+flottant.traduit(self.ui.altitude_objet.text()))*1000
        self.trajectoire.setEchelle(y,"max")
        vx=flottant.traduit(self.ui.vitesse_tangentielle_objet.text())
        vy=flottant.traduit(self.ui.vitesse_normale_objet.text())

        self.trajectoire.dessine([(x,y,0,vx,vy,0)])
        self.trajectoire.update()
        
    def initAstres(self):
        """
        Peuple le combo avec les noms d'astres
        """
        for a in astreNom:
            self.ui.astreCombo.addItem(QApplication.translate("MainWindow", a[0], None, QApplication.UnicodeUTF8))
        self.ui.astreCombo.setEditable(False)
        self.ui.astreCombo.setCurrentIndex(0)
        self.astreCourant="earth"
        self.choisi_astre(0)
        
    def connexions_signaux(self):
        QObject.connect(self.ui.Bouton_Lancer,SIGNAL("clicked()"), self.trajectoire.lance)
        QObject.connect(self.ui.Button_efface,SIGNAL("clicked()"), self.efface_trajectoire)
        QObject.connect(self.ui.bouton_video,SIGNAL("clicked()"), self.cinema)
        QObject.connect(self.ui.altitude_objet,SIGNAL("editingFinished()"), self.placeDepart)
        QObject.connect(self.ui.astreCombo,SIGNAL("currentIndexChanged(int)"),self.choisi_astre)
        QObject.connect(self.ui.radioButton_Frenet,SIGNAL("toggled(bool)"), self.choisi_coordoonees)
        #QObject.connect(self.ui.checkBox_efface,SIGNAL("stateChanged(bool)"), self.change_comportement_effacege)
        timer = QTimer(self);
        QObject.connect(timer, SIGNAL("timeout()"), self.routines);
        timer.start(1000);


        self.ui.mTerre.setReadOnly (True)
        self.ui.rTerre.setReadOnly (True)
        self.ui.auSujetAstre.setReadOnly (True)
    
    def change_comportement_effacege(self,int):
        pass
    
    def efface_trajectoire(self):
        self.trajectoire.efface()
        self.placeDepart()

    def cinema(self):
        if self.cinemaThread!=None and self.cinemaThread.isAlive():
            return
        import datetime,copy
        from numpy import arange
        date=datetime.datetime(2008,4,25)
        date=date.today()
        if self.trajectoire.traj != None:
            liste_temps=arange(0,self.trajectoire.t,self.trajectoire.dt)
            pas=10 # une image pour 10 calculs numériques
            titre=QApplication.translate("MainWindow", "Calcul de la vidéo", None, QApplication.UnicodeUTF8)
            legende=QApplication.translate("MainWindow", "Avancement ...", None, QApplication.UnicodeUTF8)
            echap=QApplication.translate("MainWindow", "Arrêt", None, QApplication.UnicodeUTF8)
            self.progress=QProgressDialog(legende,echap,0,len(liste_temps)/pas)
            self.progress.setWindowTitle(titre)
            self.progress.setValue(0)
            self.progress.show()

            # on lance le thread avec une copie de la liste calculée
            self.cinemaThread=Cinema(self.rep, self.astreCourant, date,
                                     liste_temps,
                                     copy.copy(self.trajectoire.traj.pv),
                                     "380x240",
                                     pas=pas, boum=self.trajectoire.boum,
                                     debugger=self.debug)
            self.cinemaThread.start()
            
    def routines(self):
        if self.cinemaThread!=None and self.cinemaThread.isAlive():
            self.progress.setValue(self.cinemaThread.nbImage)
            if self.progress.wasCanceled():
                self.progress.close()
                self.cinemaThread.fini=True
            if self.cinemaThread.fini:
                self.progress.setValue(self.progress.maximum()+1)
                if self.progress: self.progress.close()
            
    
    def getMasseAstre(self):
        return flottant.traduit(self.ui.masse_astre.text())
    def getDistanceAstre(self):
        return (flottant.traduit(self.ui.rayon_astre.text()) + flottant.traduit(self.ui.altitude_objet.text()))*1000 #passe en mètres
    def getVitesse(self):
        return (flottant.traduit(self.ui.vitesse_tangentielle_objet.text()),
                flottant.traduit(self.ui.vitesse_normale_objet.text()))
                
        
    def choisi_coordoonees(self,bool):
        if self.ui.radioButton_Cartesiennes.isChecked()==True :
            self.ui.label_V1.setText(QApplication.translate("MainWindow", "Vitesse selon Ox", None, QApplication.UnicodeUTF8))
            self.ui.label_V2.setText(QApplication.translate("MainWindow", "Vitesse selon Oy", None, QApplication.UnicodeUTF8))
            
        elif self.ui.radioButton_Cartesiennes.isChecked()==False :
            self.ui.label_V1.setText(QApplication.translate("MainWindow", "Vitesse Tangentielle", None, QApplication.UnicodeUTF8))
            self.ui.label_V2.setText(QApplication.translate("MainWindow", "Vitesse Normale", None, QApplication.UnicodeUTF8))


    def choisi_astre(self,int):
        """
        choisit un astre parmi la liste disponible, sur la base du texte
        couramment sélectionné dans le combo
        @param int non utiliséé
        """
        mt0=astreNom[0][2]
        rt0=astreNom[0][3]
        astre=self.ui.astreCombo.currentText()
        for a in astreNom:
            if a[0]==astre:
                self.trajectoire.choisi_astre(a[1])
                self.astreCourant=a[1]
                masse_astre=a[2]
                rayon_astre=a[3]
                self.ui.masse_astre.setText(QApplication.translate("MainWindow", masse_astre, None, QApplication.UnicodeUTF8))
                self.ui.rayon_astre.setText(QApplication.translate("MainWindow", rayon_astre, None, QApplication.UnicodeUTF8))
                mt=flottant.traduit(masse_astre)/flottant.traduit(mt0)
                rt=flottant.traduit(rayon_astre)/flottant.traduit(rt0)
                mt="%5g" %mt
                rt="%5g" %rt
                self.ui.mTerre.setText(QApplication.translate("MainWindow", mt, None, QApplication.UnicodeUTF8))
                self.ui.rTerre.setText(QApplication.translate("MainWindow", rt, None, QApplication.UnicodeUTF8))
                self.ui.auSujetAstre.setText(QApplication.translate("MainWindow", a[4], None, QApplication.UnicodeUTF8))
                self.placeDepart()
                self.trajectoire.update()
                return
        self.debug(0,"Astre inconnu : %s" %astre)
