/**
THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS WITH CODING 
INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. 
AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, INDIRECT OR 
CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE CONTENT OF SUCH FIRMWARE 
AND/OR THE USE MADE BY CUSTOMERS OF THE CODING INFORMATION CONTAINED HEREIN IN CONNECTION 
WITH THEIR PRODUCTS.
*/
package com.phoceis.STdatalogger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.phoceis.STdatalogger.R;
import com.phoceis.STdatalogger.R.drawable;

public class showGraphActivity extends Activity {
	
	private Button btnChangeSettings, btnShowGraph, btnStartStop;
	private Timer checkConnectivity;
	private TextView texOnlineOffline, texCurrentTemperature;
	private ProgressDialog progressDialog;
	private UpdateFeedTask updateFeedTask;
	private ImageView displayerTemp;
	
	private NfcAdapter mAdapter;
	private PendingIntent mPendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	
	private GraphicalView mChartView;
	
	private Boolean isOnline = true;
	public Boolean isDownloadingData = false;
	
	public ArrayList<double[]> x;
	public ArrayList<double[]> gArrayTemp; // global Array containing all acquired temperatures

	myApplication ma = (myApplication)getApplication();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        
		super.onCreate(savedInstanceState);
        setContentView(R.layout.showgraph);
        
        
        if(checkConnectivity == null)
        {
        	checkConnectivity = new Timer();
            checkConnectivity.schedule(new TimerTask() {
    			@Override
    			public void run() {
    				TimerMethod();
    			}
    		}, 0, 800);   
        }
        	            
        btnChangeSettings = (Button) this.findViewById(R.id.btnChangeSettings);
        btnStartStop = (Button) this.findViewById(R.id.btnStartStop);
        btnShowGraph = (Button) this.findViewById(R.id.btnShowGraph);
        texOnlineOffline = (TextView) this.findViewById(R.id.texOnlineOffline);
        texCurrentTemperature = (TextView) this.findViewById(R.id.texCurrentTemperature);
        displayerTemp = (ImageView) this.findViewById(R.id.displayerTemp);
        
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        mFilters = new IntentFilter[] {
                ndef,
        };
        mTechLists = new String[][] { new String[] { android.nfc.tech.NfcV.class.getName() } };         
        
        ma = (myApplication)getApplication();
        
        /* everytime the phone go from portarait to landscape and vice versa the "onCreate" is re-executed
         * So the function refreshGraph is usefull to show the graph in both views 
         */
        refreshGraph();

        /* ************************* BUTTON START STOP ***************************** */
        if(btnStartStop != null)
        {
        	this.btnStartStop.setOnClickListener(new View.OnClickListener() {			
    			@Override
    			public void onClick(View v) 
    			{
    				StartStopDatalogger();	
    			}
    		});    
        }
        
        /* *********************** BUTTON SHOW GRAPH ***************************** */
        if(btnShowGraph != null)
        {
        	this.btnShowGraph.setOnClickListener(new View.OnClickListener() {			
    			@Override
    			public void onClick(View v) 
    			{
    				if(!isDownloadingData)
    				{
    					btnShowGraph.setEnabled(false);
        				showGraphActivity.this.cancelUpdateFeedTask();
        				showGraphActivity.this.updateFeedTask = new UpdateFeedTask();
        				showGraphActivity.this.updateFeedTask.execute();
    				}
    			}
    		});
        }
        
        /* ******************* BUTTON SHOW STATS & CHANGE SETTINGS ***************************** */
        if(btnChangeSettings != null)//because in landscape mode button is not defined in xml
        {
        	this.btnChangeSettings.setOnClickListener(new View.OnClickListener() {			
    			@Override
    			public void onClick(View v) {
    				
    				NfcV nfcvTag = NfcV.get(ma.getCurrentTag());
    				
    				checkConnectivity.cancel();
    				checkConnectivity.purge();
    				checkConnectivity = null;
    				if(ma.isGraphDownloadedOnceWithoutError()==true && !isDownloadingData)
    				{
    					if (nfcvTag.isConnected())
    					{
    						try {
								nfcvTag.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
    					}
    					Intent intent = new Intent(showGraphActivity.this, com.phoceis.STdatalogger.statisticsActivity.class);
        				startActivityForResult(intent, 200);
    				}
    				else
						Toast.makeText(getApplicationContext(), "You must perform a show graph action before", 3000).show();
    			}
    		});
        }
        
    }
/* ************************************************ onCreate END ************************************************ */	
	
	
	/* *************** OVERRIDE RETURN BUTTON *******************/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	        Log.d(this.getClass().getName(), "back button pressed");
	        checkConnectivity.cancel();
			checkConnectivity.purge();
			checkConnectivity = null;
			finish();
			System.exit(0);
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	public class UpdateFeedTask extends AsyncTask<Void, Void, Void> {

	    //ProgressDialog loading;
	    @Override
	    protected void onPreExecute() 
	    { 
	    	isDownloadingData = true;
	    	progressDialog = ProgressDialog.show(showGraphActivity.this,"Please wait...", "Retrieving data ...", false);
	    	btnChangeSettings.setEnabled(false);
	    }

	    @Override
	    protected void onPostExecute(Void result) {

	    	progressDialog.dismiss();
	    	refreshGraph();
	    	btnChangeSettings.setEnabled(true);
	    	btnShowGraph.setEnabled(true);
	    	isDownloadingData = false;
	    }

	    @Override
	    protected Void doInBackground(Void... params)
	    {
			if(x==null)
				x = new ArrayList<double[]>();
			if(gArrayTemp == null)
				gArrayTemp = new ArrayList<double[]>();
			
	    	DownloadAllTemp();
	    	updateStats();
	        return null;
	    }

	}
	
	/* ____________________________StartStopDatalogger__________________________
	 * the function get the actual state of the dalalogger (Started or stopped)
	 * And change the state : 
	 * from start to stop 
	 * or 
	 * from stop to start
	 */
	private void StartStopDatalogger()
	{
		String info = "";
		NfcV nfcvTag = NfcV.get(ma.getCurrentTag());
		try 
		{
			byte[] ReadSigleBlockCommand = new byte[] { (byte) 0x0A, (byte) 0x20, (byte) 0x00, (byte) 0x00 };//Read Block 0x0000 command
			nfcvTag.close();
			nfcvTag.connect();
			byte[] response = nfcvTag.transceive(ReadSigleBlockCommand);//send command
			nfcvTag.close();
			if(response[0] == 0x00)
			{
				byte[] WriteSingleBlockCommand = new byte[]{ (byte) 0x0A,  (byte) 0x21,  (byte) 0x00,  (byte) 0x00,  (byte) 0xFF,  response[2],  response[3],  (byte) 0xFF };
				if (response[1] == 0x33)// Acquisition is running
				{
					WriteSingleBlockCommand[4] = (byte)0x44;
					info = "SUCCESS : datalogger is STOPPED";
				}
				else if (response[1] == 0x11)
				{
					WriteSingleBlockCommand[4] = (byte)0x11;
					info = "WARNING : datalogger -> LOW BATTERY";
				}
				else // Acquisition is stopped
				{
					WriteSingleBlockCommand[4] = (byte)0x11;
					info = "SUCCESS : datalogger is STARTED";
				}
				nfcvTag.close();
				nfcvTag.connect();
				response = nfcvTag.transceive(WriteSingleBlockCommand);//send command
				nfcvTag.close();
				if (response[0] == 0x00)
				{
    				Toast.makeText(getApplicationContext(), info, 500).show();
				}
			}
			
		}
		catch (Exception e)
		{
			Toast.makeText(getApplicationContext(), "ERROR : NO datalogger found", 800).show();
		}
	}
	
	
	
	/* ____________________________DownloadAllTemp__________________________
	 * the function get all the acquired temperature 
	 * fill arrayTemp 
	 * fill arrayAxis
	 */
	public void DownloadAllTemp()
	{
		int nbtemp  = ma.getNbOfAcquiredTemp();
		// the datalogger can at max have 4088 temperatures saved
		if(nbtemp<1 || nbtemp > 4088)
		{
			return;
		}
			
		int AddStart = 0;// the address where is stocked the first temperature
		int Nb32BytesBlockToRead = 0; //the M24LR64-R technology only allows multiple read by 32bytes = 64 temperatures
		byte[] AddStartByteArray = new byte[2];//address must be code on two bytes
		
		int LastErrorOcuuredOnI = -1;//usefull for Polling implementation
		int pollingCount = 0;
		
		ma.setDataCorrupted(false);
		
		//the loop define the number of "multiple read" commands to perform
		Nb32BytesBlockToRead = nbtemp/64;
		if(nbtemp%64 != 0)
		{
			Nb32BytesBlockToRead++;
		}
		
		double[] AllTemps = new double[Nb32BytesBlockToRead*64]; //Array of all downloaded temperatures in double format
		
		for(int i=0;i<Nb32BytesBlockToRead;i++)//read the right number of 32bytes blocks
		{
			AddStartByteArray = formatAddress(AddStart);//the function formatAddress (int -> byte[2])
			
			try 
			{
				NfcV nfcvTag = NfcV.get(ma.getCurrentTag());
				nfcvTag.close();
				nfcvTag.connect();
				byte[] ReadMultipleBlockCommand = new byte[]{(byte)0x0A, (byte)0x23, AddStartByteArray[0], AddStartByteArray[1], (byte)0x1F};//command read 32 bytes from AddStart
				byte[] response = nfcvTag.transceive(ReadMultipleBlockCommand);				
				nfcvTag.close();
				if(response[0] == 0x00)
				{
					double temp;//temporary variable to calculate the temp well formated ¡C
					
					int tempBrut=1,tempDecimal=2;//these are 2 index useful to navigate in the large array received in response
					for(int j=1;j<=64;j++)//format in float all 64 temperatures and fill AllTemps array with them
					{
						temp = formatTempToDouble(response[tempBrut],response[tempDecimal]);
						if(temp > 40)
						{
							temp = temp+1;
						}
						tempBrut +=2;//increment index per 2
						tempDecimal +=2;//increment index per 2
						
						AllTemps[(i*64)+(j-1)] = temp;	//(0*64)+(1-1) = 0 --> (0*64)+(2-1) = 1   --> (0*64)+(64-1) = 63
							 							//(1*64)+(1-1) = 64 --> (1*64)+(2-1) = 65  -->  etc...
					}
					
					if(i == 0)
					{
						for(int j=4;j<64;j++)
						{
							AllTemps[j-4]  = AllTemps[j];
						}
					}
					
					// if is the  last turn in the loop fill gArrayTemp with AllTemps array
					if(i == Nb32BytesBlockToRead-1)
					{
						//CLEAN TEMP ARRAY
						gArrayTemp.clear();
						ma.setArrayTemp(gArrayTemp);

						gArrayTemp.add(AllTemps);
						ma.setArrayTemp(gArrayTemp);
						
						ma.setGraphDownloadedOnceWithoutError(true);
					}
				}
			}
			// if an error occured during the read command
			catch (Exception e)
			{
				if(LastErrorOcuuredOnI == i)
				{
					pollingCount ++;
	    			if(pollingCount == 2)// if 2 succesive error occured on the same command 
	    			{
    					ma.setDataCorrupted(true);
	    				return;
	    			}
				}
				else
				{
					pollingCount = 0;//if an error occured on another command reset the polling counter
				}
				LastErrorOcuuredOnI = i;// save on what address this error read failed
				i--;//if an exception is catch we re-do the same action decrementing i
				if(i != 0)
				{
					AddStart -= (byte)0x20;//go back to the last address
				}
			}
			AddStart += (byte)0x20;//in every cases jump to the next start address
		}
		
		//the loop bellow Creates an array of index for the axis graph axe just like --> double[]{1,2,3,4,5.....NbTemp};
		double[] ArrayOfIndex = new double[nbtemp]; 
		for(int h=1;h<=nbtemp;h++)
		{
			ArrayOfIndex[h-1] = h;
		}
		// CLEAN X ARRAY
		x.clear();
		ma.setArrayAxis(x);
		
		showGraphActivity.this.x.add(ArrayOfIndex);// add axis Array to the List<>
		ma.setArrayAxis(x);
	}
	
	
	
	
	
	private void TimerMethod()
	{
		this.runOnUiThread(Timer_Tick);
	}

	/* ____________________________TIMER__________________________
	 * the function is executed every 800 ms
	 * display connected/not connected information
	 * display the last acquired temperature
	 */
	private Runnable Timer_Tick = new Runnable() {
		@Override
		public void run() {
			if (isDownloadingData) 
				return; 

			try 
			{
				NfcV nfcvTag = NfcV.get(ma.getCurrentTag());
				byte[] ReadStatusByte = new byte[] { (byte) 0x0A, (byte) 0x20, (byte) 0x00, (byte) 0x00 };//Read Block 0x0000
				nfcvTag.close();
				nfcvTag.connect();
				byte[] response2 = nfcvTag.transceive(ReadStatusByte);
				nfcvTag.close();
				if(response2[0] == (byte)0x00)// Block 0x0000 was read !
				{
					
						setIsOnline(true);
					ma.setConfiguration(response2);
					ma.setCurrentDelay(response2[3]);
					ma.setCurrentOverwrite(response2[2]);
					if(response2[1] == 0x33)
					{
						btnStartStop.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_stop_datalogger_off));
					}	
				
					else if (response2[1] == 0x44)
					{
						btnStartStop.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_start_datalogger_on));
					}
						
					
					byte[] ReadNbTempCommand = new byte[] { (byte) 0x0A, (byte) 0x20, (byte) 0x01, (byte) 0x00 };//Read Block 0x0001
					nfcvTag.close();
					nfcvTag.connect();
					byte[] response3 = nfcvTag.transceive(ReadNbTempCommand);
					nfcvTag.close();
					if(response3[0] == (byte)0x00)// Block 0x0001 was read !
					{
						//number of acquired temp is coded on 2 bytes (response[1] & response[2])
						int NbTemp = response3[1] + response3[2]*256;
						if(response3[1]<0)
							NbTemp += 256;
						
						ma.setNbOfAcquiredTemp(NbTemp);
						
						if(NbTemp != 0)
						{
							int BlockLastTemp = 2;
							if(NbTemp%2 == 0)//NbTemp Parity
								BlockLastTemp = (NbTemp/2) + 1;
								
							else//NbTemp non-Parity
								BlockLastTemp = ((NbTemp+1)/2) + 1;
							
							byte[] LastTempAddAddress = formatAddress(BlockLastTemp);
							
							byte[] ReadLastTempCommand = new byte[] { (byte) 0x0A, (byte) 0x20, LastTempAddAddress[0], LastTempAddAddress[1] };//Read Block where last temp was recorded
							
							nfcvTag.connect();
							byte[] response4 = nfcvTag.transceive(ReadLastTempCommand);	
							nfcvTag.close();
							if(response4[0] == (byte)0x00)// Block cointaiining lastAcquired temp was read !
							{
								double tempActual;
								String temp;
								if(NbTemp%2 == 0)//NbTemp Parity
								{
									tempActual = formatTempToDouble(response4[3],response4[4]);
									
								}
								else//NbTemp non-Parity
								{
									tempActual = formatTempToDouble(response4[1],response4[2]);
								}
								if (tempActual >40)
								{
									tempActual = tempActual +1;
								}
								temp = Double.toString(tempActual) + " ¡C";
								if(texCurrentTemperature != null)
									texCurrentTemperature.setText(temp); // display as string format the last acquired temperature
								ma.setCurrentTemp(tempActual);
							}
						}
					}
					
				}
				
				nfcvTag.close();
				

			}
			catch (Exception e)
			{
				setIsOnline(false);	
			}
		}
	};
	
	/* ____________________________refreshGraph__________________________
	 * the function display the graph
	 */
	private void refreshGraph()
	{
		myApplication ma = (myApplication)getApplication();
		
		if(ma.isGraphDownloadedOnceWithoutError() == false || ma.getArrayTemp().size() == 0)
			return;
		
		String[] titles = new String[] { "temperatures"}; 
        int[] colors = new int[] { Color.BLACK};
        PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
        XYMultipleSeriesRenderer renderer = com.phoceis.STdatalogger.AbstractDemoChart.buildRenderer(colors, styles);
        int length = renderer.getSeriesRendererCount();
        for (int i = 0; i < length; i++) {
          ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
        }        
        AbstractDemoChart.setChartSettings(renderer, "", "Sample #", "Temperature", 0, ma.getNbOfAcquiredTemp(), ma.getMinTemp()-1, ma.getMaxTemp()+1,
            Color.DKGRAY, Color.DKGRAY);
//        renderer.setLegendHeight(16);
//        renderer.setXLabels(5);
//        renderer.setYLabels(5);
//        renderer.setPointSize(10);
//        renderer.setShowGrid(false);
//        renderer.setXLabelsAlign(Align.CENTER);
//        renderer.setMarginsColor(0xffff);
//        renderer.setAxisTitleTextSize(8);
//        renderer.setAxisTitleTextSize(12);
//        renderer.setLabelsTextSize(12);
//        renderer.setLegendTextSize(12);
        
        renderer.setLegendHeight(20);
        renderer.setXLabels(5);
        renderer.setYLabels(5);
        renderer.setPointSize(14);
        renderer.setShowGrid(false);
        renderer.setXLabelsAlign(Align.CENTER);
        renderer.setMarginsColor(0xffff);
        renderer.setAxisTitleTextSize(16);
        renderer.setLabelsTextSize(16);
        renderer.setLegendTextSize(16);
        
        renderer.setShowLegend(true);
        renderer.setZoomEnabled(false, false);
        renderer.setAntialiasing(true);
        renderer.setYLabelsAlign(Align.RIGHT);
        renderer.setPanLimits(new double[] { 0, ma.getNbOfAcquiredTemp(), ma.getMinTemp()-1, ma.getMaxTemp()+1});
        renderer.setZoomLimits(new double[] { -100, ma.getNbOfAcquiredTemp(),ma.getMinTemp()-1,ma.getMaxTemp()+1});
        
        LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
        
        layout.removeAllViews();
        
        mChartView = ChartFactory.getLineChartView(this, AbstractDemoChart.buildDataset(titles, ma.getArrayAxis(), ma.getArrayTemp()),renderer); 
 
        layout.addView(mChartView, new LayoutParams(LayoutParams.WRAP_CONTENT , LayoutParams.WRAP_CONTENT ));  
     
	}
	
	private Boolean getIsOnline() {
		return isOnline;
	}

	private void setIsOnline(Boolean isOnline) {
		
		this.isOnline = isOnline;
		if (texOnlineOffline != null && btnShowGraph != null && btnStartStop != null)
		{
			texOnlineOffline.setTextColor(isOnline?getResources().getColor(R.color.green):getResources().getColor(R.color.red));
			texOnlineOffline.setText(isOnline?"connected":"not connected");
			if(isOnline)
				displayerTemp.setImageDrawable(getResources().getDrawable(drawable.displayer_on));
			else
				displayerTemp.setImageDrawable(getResources().getDrawable(drawable.displayer_off));
		}
		
		
	}
	
	
	private void cancelUpdateFeedTask()
	{
		if(showGraphActivity.this.updateFeedTask != null && showGraphActivity.this.updateFeedTask.isCancelled())
		{
			if(progressDialog != null)
			{
				progressDialog.dismiss();
			}
			showGraphActivity.this.updateFeedTask.cancel(true);
		}
	}
	
	@Override
    public void onResume() {
        super.onResume();
        
        if(checkConnectivity == null)
        {
        	checkConnectivity = new Timer();
            checkConnectivity.schedule(new TimerTask() {
    			@Override
    			public void run() {
    				TimerMethod();
    			}
    		}, 0, 800);
        }
          
        mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
    }

    @Override
    public void onNewIntent(Intent intent) {
       Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);     
       myApplication ma = (myApplication)getApplication();
       ma.setCurrentTag(tagFromIntent);
       
    }

    @Override
    public void onPause() {
        super.onPause();
        mAdapter.disableForegroundDispatch(this);
        //System.exit(0);
    }
	
   
	
	
	/*
	 * this function format the address with the M24LR64-R chip format
	 * ex : byte[] result = formatAddress(1000);
	 * 		in this case result ->  {[0x03][0xE8]}
	 */
	public byte[] formatAddress (int iAdd)
	{
		int add1 ;
		add1 = iAdd%256;
		int add2 ;
		add2 = iAdd/256;
		byte[] bAddress = new byte[]{(byte)add1,(byte)add2};
		return bAddress;
	}
	
	/*
	 * this function convert the two temperatures byte in a float value
	 * ex : float result =  formatTempToDouble(0x19, 0x80);
	 * 		in this case result -> 25,5¡C
	 */
	public double formatTempToDouble(byte TemperatureByte1,byte TemperatureByte2)
	{
		double temperature = TemperatureByte1;
		
		if(temperature > 240)//the temp is negative
		{
			temperature -= 255;
			if(TemperatureByte2 == -128)
			{
				temperature -= 0.5;
			}
		}
		else
		if(TemperatureByte2 == -128)
		{
			temperature += 0.5;
		}
		return temperature;
	}
	
	public void updateStats ()
	{
		myApplication ma = (myApplication)getApplication();
		if(ma.isGraphDownloadedOnceWithoutError()==false || ma.isDataCorrupted())
		{
			return;
		}
		ma.setMaxTemp(-50);
		ma.setMinTemp(50);
		ma.setCurrentDelay(ma.getConfiguration()[3]);
		ma.setCurrentOverwrite(ma.getConfiguration()[2]);
		ma.setAvgTemp(0);
		float Avg =0 ;
		int localNbTemp = ma.getNbOfAcquiredTemp();
		ArrayList<double[]> localArrayTemp = ma.getArrayTemp();
		
		
		if(localArrayTemp.size() != 0 && localNbTemp!=0)
		{
			for(int i = 0; i< localNbTemp ; i++)
			{
				if(localArrayTemp.get(0)[i] == 0)
				{
					float maxT = ma.getMaxTemp(); 
				}
				if(localArrayTemp.get(0)[i] > ma.getMaxTemp())
				{
					ma.setMaxTemp((float)localArrayTemp.get(0)[i]);
				}
				if(localArrayTemp.get(0)[i] < ma.getMinTemp())
				{
					ma.setMinTemp((float)localArrayTemp.get(0)[i]);
				}
				Avg += (float)localArrayTemp.get(0)[i];
			}
			Avg = Avg / localNbTemp;
			if(Avg>-50 && Avg < 50)
			{
				ma.setAvgTemp(Avg);
			}
		}
		else
		{
			Toast.makeText(getApplicationContext(), "Advice : You should perform a Show graph action first", 1500).show();
		}
	}
	
}
