package sliz.elektromery;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import sliz.elektromery.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.view.View.OnClickListener;

public class DatabaseActivity extends Activity  
{
	ListView listView;
		
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.database_view);
		
		listView = (ListView) findViewById(R.id.listView1);
		
		MyAdapter adapter = new MyAdapter();
		
      
      // Assign adapter to ListView
      listView.setAdapter(adapter);
      listView.setOnItemClickListener(new OnItemClickListener() {
    	  @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                  long arg3)  {
              
              MyData actData = (MyData) listView.getAdapter().getItem(arg2);
              
              
              Toast.makeText(getBaseContext(), actData.Date + ", " + actData.Values, Toast.LENGTH_SHORT).show();
              
	          }
		});
      
      
      scrDatabaseViewEvents();
      
      
      this.setTitle(appSettings.mSelectedFile);
	}
	
	private void backToMenu() {
		Intent intnscnd = new Intent(DatabaseActivity.this, MenuActivity.class);
		startActivity(intnscnd);
		DatabaseActivity.this.finish();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			backToMenu();
		}

		// Pass other events along their way up the chain
		return super.onKeyDown(keyCode, event);
	}
	
	void scrDatabaseViewEvents()
	{
		Button btnBack = (Button) findViewById(R.id.btn_database_back);
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				backToMenu();
			}
		});
		
		Button btnGraph = (Button)findViewById(R.id.btn_database_graph);
		btnGraph.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				// Check data length
				if(listView.getAdapter().getCount() > 0)
				{
					// Show graph
					Intent intnscnd = new Intent(DatabaseActivity.this, GraphActivity.class);
			        startActivity(intnscnd);
			        DatabaseActivity.this.finish();
				}
				else
				{
					showAlert();
				}
			}
		});
		
	}
	
	void showAlert()
	{
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	String strTitle = appSettings.mSelectedFile + ": " + getString(R.string.strNoData);
		builder.setTitle(strTitle);
		
		builder.setPositiveButton(R.string.strOK, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		
		builder.show();
	}

	public static List<MyData> getDataList()
	{
		List<MyData> MyDataList = new ArrayList<MyData>();
		
		// Load data from selected file
		FileInputStream is;
		BufferedReader reader;
		final File file = new File(appSettings.mAppDirFiles, appSettings.mSelectedFile);

		if (file.exists()) {
		    try {
				is = new FileInputStream(file);
				reader = new BufferedReader(new InputStreamReader(is));
			    
		        try {
		        	String line = reader.readLine();
				    while(line != null){
				    	String[] separated = line.split(";");
				    	if(separated.length == 3)
				    	{
				    		MyData newDataItem = new MyData();
				    		// Format date				    		
				    		newDataItem.DateMS = Long.parseLong(separated[0]);
				    		Date date = new Date(newDataItem.DateMS);
				    		CharSequence chDate = android.text.format.DateFormat.format("dd.MM. yyyy hh:mm:ss", date);							
							newDataItem.Date = chDate.toString();
							newDataItem.Values = separated[2];
							MyDataList.add(newDataItem);
				    	}
				    	line = reader.readLine();
				    }
				    reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			    
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		   
		}
		
		
//		for(int i = 0 ; i < 20 ; i++)
//		{
//			MyData newDataItem = new MyData();
//			newDataItem.Name = "Name " + i;
//			newDataItem.Values = "Values " + i;
//			MyDataList.add(newDataItem);
//		}
		return MyDataList;
	}


	class MyAdapter extends BaseAdapter
	{
		List<MyData> MyDataList = getDataList();
	
		@Override
		public int getCount() {
			
			return MyDataList.size();
		}
	
		@Override
		public MyData getItem(int arg0) {
			
			return MyDataList.get(arg0);
		}
	
		@Override
		public long getItemId(int arg0) {
			return arg0;
		}
	
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {		
			if(arg1 == null)
			{
				// Create inflater to get access to layout
				LayoutInflater inflater = (LayoutInflater) DatabaseActivity.this.getSystemService(
																		Context.LAYOUT_INFLATER_SERVICE);
				arg1 = inflater.inflate(R.layout.my_list_item, arg2, false);
			}
			
			TextView chapterName = (TextView)arg1.findViewById(R.id.txt_set_frame_method);
	        TextView chapterVals = (TextView)arg1.findViewById(R.id.textView2);
			
	        MyData actItem = MyDataList.get(arg0);
	        chapterName.setText(actItem.Values  + " [kWh]");
	        chapterVals.setText(actItem.Date);
	        
			return arg1;
		}	
		
		
	}	
  
}